图片延迟加载效果(图片需自己添加)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片的延迟加载效果</title> <style> * { margin: 0; padding: 0; } #outer { 1200px; margin: 100px auto 0; } #outer h1 { height: 30px; line-height: 30px; text-align: center; font-size: 30px; margin-bottom: 20px; } #con img { float: left; 590px; height: 350px; margin: 5px; } </style> </head> <body> <div id="outer"> <h1>图片展示</h1> <div id="con"> <img orc="images/001.jpg" alt=""> <img orc="images/002.jpg" alt=""> <img orc="images/003.jpg" alt=""> <img orc="images/004.jpg" alt=""> <img orc="images/005.jpg" alt=""> <img orc="images/006.jpg" alt=""> <img orc="images/007.jpg" alt=""> <img orc="images/008.jpg" alt=""> <img orc="images/009.jpg" alt=""> <img orc="images/010.jpg" alt=""> <img orc="images/011.jpg" alt=""> <img orc="images/012.jpg" alt=""> <img orc="images/013.jpg" alt=""> <img orc="images/014.jpg" alt=""> <img orc="images/015.jpg" alt=""> <img orc="images/016.jpg" alt=""> <img orc="images/017.jpg" alt=""> <img orc="images/018.jpg" alt=""> <img orc="images/019.jpg" alt=""> <img orc="images/020.jpg" alt=""> <img orc="images/021.jpg" alt=""> <img orc="images/022.jpg" alt=""> </div> </div> <script> window.onload = window.resize = window.onscroll = function() { var $ = function(id) { return document.getElementById(id); } var imgs = $('con').children; var scrolltop = document.documentElement.scrollTop || document.body.scrollTop; var windowH = document.documentElement.clientHeight || document.body.clientHeight; console.log(imgs.length); //获取元素到body的距离 function offsetTL(obj) { var l = 0, t = 0; while(obj) { l = l + obj.offsetLeft + obj.clientLeft; t = t + obj.offsetTop + obj.clientTop; obj = obj.offsetParent; } return {left: l, top: t}; } for (var i = 0; i < imgs.length; i++) { if(offsetTL(imgs[i]).top <= scrolltop + windowH) { imgs[i].src = imgs[i].getAttribute('orc'); } } } </script> </body> </html>