這篇文章主要介紹了使用原生javascript實現圖片滾動、延時加載功能,思路與方法均分享給大家,希望對大家能有所幫助。
實現效果:下拉捲軸時,圖片出現在可見區域時,才開始載入
思路:
(1)img標籤,把真實的圖片位址,放在自己設定的屬性裡面,如lazy-src
(2)取得img離頁面的高度(在JQ裡是offset().top),原生是:
img. getBoundingClientRect().top document.body.scrollTop||document.documentElement.scrollTop
(3)判斷img出現的位置是否在可見區域:
在瀏覽器的可見區域, justTop>scrollTop&&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); } } }
效果圖:
以上就是本章的全部內容,更多相關教學請造訪
JavaScript影片教學