<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>单张图片延迟加载</title> <style type="text/css"> * { margin: 0; padding: 0; font-family: "sans-serif"; font-size: 14px; } .banner { width: 380px; height: 300px; margin: 1000px auto; border: 1px solid green; background: url(images/3.jpg) center no-repeat; } .banner img { display: none; width: 100%; height: 100%; } </style> </head> <body> <div class="banner" id="banner"> <img src="" trueImg="images/5.jpg"/> </div> <script type="text/javascript"> var banner = document.getElementById("banner"), imgFir = banner.getElementsByTagName("img")[0]; window.onscroll = function () { if (banner.flag) { return; } var A = banner.offsetHeight + offset(banner).top; var B = win("clientHeight") + win("scrollTop"); if (A < B) { var oImg = document.createElement("img"); oImg.src = imgFir.getAttribute("trueImg"); oImg.onload = function () { imgFir.src = this.src; imgFir.style.display = "block"; oImg = null; } banner.flag = true; } } //->offset:获取页面中任意元素距离BODY的偏移 function offset(curEle) { var disLeft = curEle.offsetLeft, disTop = curEle.offsetTop, par = curEle.offsetParent; while (par) { if (navigator.userAgent.indexOf("MSIE 8") === -1) {//不是标准的IE8浏览器,我们才累加边框 disLeft += par.clientLeft; disTop += par.clientTop; } disLeft += par.offsetLeft; disTop += par.offsetTop; par = par.offsetParent; } return {left: disLeft, top: disTop}; } //->win:操作浏览器的盒子模型信息 function win(attr, value) { if (typeof value === "undefined") { return document.documentElement[attr] || document.body[attr]; } document.documentElement[attr] = value; document.body[attr] = value; } </script> </body> </html>
单张图片延迟加载
最新推荐文章于 2022-01-25 21:27:55 发布