1. 为翻页按钮添加功能
- 当一个页面需要滚动条加载更多内容,添加翻页功能。
<body>
<img src="images1/default.png" data-src="./images1/5.jpg" alt="" width="660" />
</body>
<script>
document.documentElement.style.height = “1000px”;
console.log(document.documentElement.scrollTop);
2.当鼠标移出时,图片的每隔2秒的自动播放(2000毫秒)
window.onscroll = () => {
const img = document.querySelector(“img”);
setTimeout(() => {
img.src = img.dataset.src;
}, 2000);
};
</script>
案例:
- 放图片到容器
<body>
<img src="images2/temp.jpg" alt="" data-src="images2/img-1.jpg" /><div class="container">
<img src="images2/temp.jpg" alt="" data-src="images2/img-2.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-3.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-4.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-5.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-6.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-7.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-8.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-9.jpg" />
<img src="images2/temp.jpg" alt="" data-src="images2/img-10.jpg" />
- 设置格式
<style>
.container {
width: 500px;
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
.container img {
width: 100%;
}
</style> - 懒加载layzyload,第一屏马上显示: clientHeight,offsetTop,scrollTop
<script>
const imgs = document.querySelectorAll(“.container img”);
const clientHeight = document.documentElement.clientHeight;
window.addEventListener(“scroll”, layzyload);
window.addEventListener(“load”, layzyload);
function layzyload() {
let scrollTop = document.documentElement.scrollTop;
imgs.forEach((img) => {
if (img.offsetTop < clientHeight + scrollTop) {
setTimeout(function () {
img.src = img.dataset.src;
}, 500);
}
});
}
</script>