javascript 图片 滚动加载

以下代码出自国永哥哥的博客呐,好的东西一定要拿下来收藏 的啦http://www.cnblogs.com/focuslgy/p/3194502.html

html :
<div id="box">
            <ul>
                <li>
                    <img width="199" height="150" src="p.png" alt="" lazy-src="test_img/1.jpg">
                </li>
               
            </ul>
 </div>

  

  javascript:
function ImgScrollLoad(option){
this.oImg = document.getElementById(option.wrapID).getElementsByTagName('img'); this.sHolder_src = option.holder_src; this.init(); } ImgScrollLoad.prototype = { init:function(){ this.loadImg(); var _that = this, timer = null; // 滚动:添加定时器,防止频繁调用loadImg函数 window.onscroll = function(){ clearTimeout(timer); timer = setTimeout(function(){ _that.loadImg(); },100); } }, loadImg:function(){ for(var n=0;n<this.oImg.length;n++){ //获取图片占位符图片地址 var hSrc = this.oImg[n].getAttribute(this.sHolder_src); if(hSrc){ var scrollTop = document.body.scrollTop||document.documentElement.scrollTop, windowHeight = document.documentElement.clientHeight, offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop, imgHeight = this.oImg[n].clientHeight, justTop = offsetTop + imgHeight; if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight) || offsetTop == scrollTop){ this.isLoad(hSrc,n); } } } }, isLoad:function(src,n){ var src = src, o_img = new Image(), _that = this; o_img.onload = function(){ _that.oImg[n].setAttribute('src',src); _that.oImg[n].removeAttribute(_that.sHolder_src); } o_img.src = src; } } //实例化 new ImgScrollLoad({'wrapID':'box','holder_src':'lazy-src'});

 

原文地址:https://www.cnblogs.com/enen/p/3194723.html