<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片懒加载</title>
<style>
.img-box{
300px;
height: 300px;
overflow: hidden;
margin:30px auto;
background-color: #f2f2f2;
}
.img-box img{
max- 100%;
}
</style>
</head>
<body>
<ul>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
<li class="img-box">
<img src="img/loading.gif" alt="" data-origin="img/smile.jpg" class="lazyload">
</li>
</ul>
<script>
//获取所有需要懒加载的img元素
let images = document.querySelectorAll("img.lazyload");
//创建观察器 IntersectionObserver callback options
let observer = new IntersectionObserver(entries => {
entries.forEach(item => {
if (item.isIntersecting) {
item.target.src = item.target.dataset.origin; // 开始加载图片
observer.unobserve(item.target); // 停止监听已开始加载的图片
}
});
},{
rootMargin: "0px 0px -300px 0px"//距离上右下左
});
//逐个监听
images.forEach(item => observer.observe(item));
</script>
</body>
</html>
懒加载加动画
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>懒加载加动画</title> <style> .img-box{ 300px; height: 300px; overflow: hidden; margin:30px auto; background-color: #f2f2f2; } .img-box.show{ animation: left 1s ease; } .img-box.show:nth-child(2n){ animation: right 1s ease; } @keyframes left { from { opacity: 0; transform: translate(-100px, 20px); } to { opacity: 1; } } @keyframes right { from { opacity: 0; transform: translate(100px, 20px); } to { opacity: 1; } } </style> </head> <body> <ul> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> <li class="img-box"> </li> </ul> <script> //获取所有需要懒加载的img元素 let images = document.querySelectorAll(".img-box"); //创建观察器 IntersectionObserver callback options let observer = new IntersectionObserver(entries => { entries.forEach(item => { if (item.isIntersecting) { item.target.src = item.target.classList.add('show'); // 开始加载图片 observer.unobserve(item.target); // 停止监听已开始加载的图片 } }); },{ rootMargin: "0px 0px 0px 0px" }); //逐个监听 images.forEach(item => observer.observe(item)); </script> </body> </html>
link:https://juejin.im/post/5d665133e51d4561c83e7c83