Image lazy loading,
Idea: When the mouse slides to the height of the corresponding image, the image is loaded;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div{ width: 575px; height: auto; overflow: hidden; border: red 1px solid; margin: 0 auto; /*给该div设置定位*/ position: relative; } #div img{ width: 267px; height: 396px; margin-left: 10px; border: 1px solid #000; } </style> <script type="text/javascript"> function getPos(obj){ var l = 0; var t = 0; while(obj){ l += obj.offsetLeft; t += obj.offsetTop; obj = obj.offsetParent; } return {left:l ,top : t} } window.onload = window.onscroll = function(){ //获取到img var aImg = document.getElementsByTagName("img"); //获取到它的scrollTop 值 考虑兼容问题 var oScrollTop = document.documentElement.scrollTop || document.body.scrollTop; // clientHeight = 上下padding + height var clientH = document.documentElement.clientHeight; //循环遍历每一项通过调用获取到每一个i 项对象的top 值 for (var i = 0;i<aImg.length;i++) { var aImgTop = getPos(aImg[i]).top; // 当滚动的时候进行判断,看他的滚动的高度加上它的clientHeight 是否比它的 top 值大 // 如果大或等于说明滚动到当前位置可以加载图片 if (oScrollTop + clientH >= aImgTop) { // 进行图片的加载 aImg[i].src = aImg[i].getAttribute("_src"); } } } </script> </head> <body> <div id="div"> <img _src="../img/1.jpg"/> <img _src="../img/2.jpg"/> <img _src="../img/3.jpg"/> <img _src="../img/4.jpg"/> <img _src="../img/6.jpg"/> <img _src="../img/7.jpg"/> <img _src="../img/1.jpg"/> <img _src="../img/2.jpg"/> <img _src="../img/3.jpg"/> <img _src="../img/4.jpg"/> <img _src="../img/6.jpg"/> <img _src="../img/7.jpg"/> <img _src="../img/3.jpg"/> <img _src="../img/4.jpg"/> <img _src="../img/6.jpg"/> <img _src="../img/7.jpg"/> </div> </body> </html>
When Loading mode commonly used when there is a layout similar to waterfall flow
<script> var num = document.getElementsByTagName('img').length; var img = document.getElementsByTagName("img"); var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历 lazyload(); //页面载入完毕加载可是区域内的图片 window.onscroll = lazyload; function lazyload() { //监听页面滚动事件 var seeHeight = document.documentElement.clientHeight; //可见区域高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度 for (var i = n; i < num; i++) { if (img[i].offsetTop < seeHeight + scrollTop) { if (img[i].getAttribute("src") == "") { img[i].src = img[i].getAttribute("data-src"); } n = i + 1; } } } </script>
<script> var n = 0, imgNum = $("img").length, img = $('img'); lazyload(); $(window).scroll(lazyload); function lazyload(event) { for (var i = n; i < imgNum; i++) { if (img.eq(i).offset().top < parseInt($(window).height()) + parseInt($(window).scrollTop())) { if (img.eq(i).attr("src") == "") { var src = img.eq(i).attr("data-src"); img.eq(i).attr("src", src); n = i + 1; } } } } </script>
The above is the detailed content of JS implementation of image lazy loading tutorial. For more information, please follow other related articles on the PHP Chinese website!