這篇文章主要介紹了使用原生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);
}
}
}
},
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插件實現的差吧,代碼還簡潔,小伙伴們參考下吧。