【每日一练】219—图片库懒加载瀑布流的实现

每日一练11个月前发布 admin
2,107 0

图片库的最终效果:

【每日一练】219—图片库懒加载瀑布流的实现

实现代码:

HTML:

<!DOCTYPE html>
<html lang=”en”>
  <head>
    <meta charset=”UTF-8″ />
    <meta http-equiv=”X-UA-Compatible” content=”IE=edge” />
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ />
    <title>第219练</title>
    <link rel=”stylesheet” href=”style.css” />
  </head>
  <body>
    <div class=”image-container”>
      <img src=”https://picsum.photos/300?random=1″ />
      <img src=”https://picsum.photos/300?random=2″ />
      <img src=”https://picsum.photos/300?random=3″ />
      <img src=”https://picsum.photos/300?random=4″ />
      <img src=”https://picsum.photos/300?random=5″ />
      <img src=”https://picsum.photos/300?random=6″ />
    </div>
    <button class=”btn”>点击加载更多</button>
    <script src=”index.js”></script>
  </body>
</html>

CSS:

body {
  margin: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: brown;
}
.image-container {
  text-align: center;
}
.image-container img {
  margin: 10px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  background-color: lightgray;
  width: 300px;
  height: 300px;
}
.btn {
  background-color: slateblue;
  border: none;
  padding: 10px 20px;
  margin: 20px;
  color: white;
  border-radius: 5px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  cursor: pointer;
}
.btn:hover {
  opacity: 0.9;
}

JS:

const imageContainerEl = document.querySelector(“.image-container”);
const btnEl = document.querySelector(“.btn”);
btnEl.addEventListener(“click”, () => {
  imageNum = 10;
  addNewImages();
});
function addNewImages() {
  for (let index = 0; index < imageNum; index++) {
    const newImgEl = document.createElement(“img”);
    newImgEl.src = `https://picsum.photos/300?random=${Math.floor(
      Math.random() * 2000
    )}`;
    imageContainerEl.appendChild(newImgEl);
  }
}

 

© 版权声明

相关文章

暂无评论

暂无评论...