<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>懒加载</title> <style> img { display: block; margin: 0 auto 50px; width: 960px; height: 540px; } .opacity { animation: .5s ani linear; -webkit-animation: .5s ani linear; -moz-animation: .5s ani linear; } @keyframes ani { 0% { opacity: 0; } 50% { opacity: .5; } 100% { opacity: 1; } } </style> </head> <body> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzutb8xegj31hc0u0k77.jpg" alt=""> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzutz6y29j31hc0u0ak4.jpg" alt=""> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuu8igyyj31hc0u0qgv.jpg" alt=""> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuug47wrj31hc0u0k2q.jpg" alt=""> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuuowb0hj31hc0u0akx.jpg" alt=""> <img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuuyjapsj31hc0u0ths.jpg" alt=""> </body> <script> var len = document.getElementsByTagName('img').length; var img = document.getElementsByTagName("img"); var n = 0; // 存储图片加载到的位置,避免每次都从第一张图片开始遍历 lazyload();// 页面载入完毕加载可视区域内的图片 // 监听页面滚动事件 window.onscroll = function () { lazyload(); }; // 封装懒加载函数 function lazyload() { // 可见区域高度 var seeHeight = document.documentElement.clientHeight; // 滚动条距离顶部高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; for (var i = n; i < len; i++) { // 如果图片距顶部距离小于可见区域高度与滚动条距离顶部高度之和时,才显示图片 if (img[i].offsetTop < seeHeight + scrollTop) { if (img[i].getAttribute("src") == "") { img[i].setAttribute('class', 'opacity'); img[i].src = img[i].getAttribute("data-src"); } n = i + 1; } } } </script> </html>