window.onscroll = () => {
const img = document.querySelector(“img”);
setTimeout(() => {
img.src = img.dataset.src;
}, 2000);
};
</script>
案例:
<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>
<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>