原生js图片懒加载特效

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <style>
 7         *{
 8             margin:0;
 9             padding:0;
10         }
11         img{
12             width: 100%;
13             height: 500px;
14         }
15     </style>
16 </head>
17 <body>
18     <img asrc="1.jpg" alt="">
19     <img asrc="2.jpg" alt="">
20     <img asrc="3.jpg" alt="">
21     <img asrc="4.jpg" alt="">
22     <img asrc="5.jpg" alt="">
23     <script>
24         //document.body.scrollTop 滚动条高度
25         //document.documentElement.clientHeight 网页可见区域高度
26         var img=document.getElementsByTagName('img');
27         function update(){//更新数据
28             for (var i = 0; i < img.length; i++) {
29             if(document.body.scrollTop+document.documentElement.clientHeight>img[i].offsetTop){
30                     img[i].src=img[i].getAttribute('asrc');
31                 }
32             }
33         }
34         window.addEventListener('scroll',update)
35         update();
36     </script>
37 </body>
38 </html>
原文地址:https://www.cnblogs.com/shuaihan/p/7296675.html