实现效果:下拉滚动条时,图片出现在可见区域时,才开始加载
思路:
(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);
}
}
}
},
isLoad:function(src,n){
var src = src,
n = n,
o_img = new Image(),
_that = this;
o_img.onload = (function(n){
_that.oImg[n].setAttribute('src',src);
_that.oImg[n].removeAttribute(_that.sHolder_src);
})(n);
o_img.src = src;
},
int:function(){
this.loadImg();
var _that = this,
timer = null;
// 滚动:添加定时器,防止频繁调用loadImg函数
window.onscroll = function(){
clearTimeout(timer);
timer = setTimeout(function(){
_that.loadImg();
},100);
}
}
}
效果图:
以上就是本文的全部内容了,实现的效果不比jQuery插件实现的差吧,代码还简洁,小伙伴们参考下吧。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!