原生javascript实现图片滚动、延时加载功能

实现效果:下拉滚动条时,图片出现在可见区域时,才开始加载

思路:

(1)img标签,把真实的图片地址,放在自己设置的属性里面,如 lazy-src

(2)获取img离页面的高度(在JQ里是offset().top),原生是:

   img.getBoundingClientRect().top + document.body.scrollTop||document.documentElement.scrollTop

(3)判断img出现的位置是否在可见区域里:

  .在浏览器的可见区域,justTop>scrollTop&&offsetTop<(scrollTop+windowHeight),这里的justTop是图片的offsetTop+图片高度

复制代码 代码如下:


//保存document在变量里,减少对document的查询
            var doc = document;
            for(var n=0,i = this.oImg.length;n<i;n++){
                //获取图片占位符图片地址
                var hSrc = this.oImg[n].getAttribute(this.sHolder_src);
                if(hSrc){
                    var scrollTop = doc.body.scrollTop||doc.documentElement.scrollTop,
                        windowHeight = doc.documentElement.clientHeight,
                        offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop,
                        imgHeight = this.oImg[n].clientHeight,
                        justTop = offsetTop + imgHeight;
                    // 判断图片是否在可见区域
                    if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight)){

this.isLoad(hSrc,n);
                    }
                }

}

以下为详细代码:

复制代码 代码如下:


function LGY_imgScrollLoad(option){
        this.oImg = document.getElementById(option.wrapID).getElementsByTagName('img');
        this.sHolder_src = option.holder_src;
        this.int();
    }
    LGY_imgScrollLoad.prototype = {
        loadImg:function(){
            //保存document在变量里,减少对document的查询
            var doc = document;
            for(var n=0,i = this.oImg.length;n<i;n++){
                //获取图片占位符图片地址
                var hSrc = this.oImg[n].getAttribute(this.sHolder_src);
                if(hSrc){
                    var scrollTop = doc.body.scrollTop||doc.documentElement.scrollTop,
                        windowHeight = doc.documentElement.clientHeight,
                        offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop,
                        imgHeight = this.oImg[n].clientHeight,
                        justTop = offsetTop + imgHeight;
                    // 判断图片是否在可见区域
                    if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight)){
                        //alert(offsetTop);
                        this.isLoad(hSrc,n);
                    }
                }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxgyf.html