JS

懒加载初始版

2019-01-23  本文已影响5人  匆匆那年_海

懒加载初始版

function getFixed(obj){
  //获取非行间属性
  function getStyle(obj,styleName){
    if (obj.currentStyle){
      return obj.currentStyle[styleName];
    }
    else{
      return getComputedStyle(obj,null)[styleName];
    }
  }
  //要获取图片相对网页顶部的距离,但图片有被定位的父级
  var iLeft=0; 
  var iTop=0;
  var oParent=obj;
  while(oParent){
    if (oParent.tagName=="HTML"){
      break;
    }
    iLeft+=oParent.offsetLeft;
    iTop+=oParent.offsetTop;
    if (oParent!=obj){
                    //offsetLeft不包括边框,因此要把边框加上
      iLeft+=parseInt(getStyle(oParent,"borderWidth"));
      iTop+=parseInt(getStyle(oParent,"borderWidth"));
    }
    oParent=oParent.offsetParent;
  }
  return [iLeft,iTop];//当 break 后itop就是图片相对网页顶部的距离
}
window.onload=window.onscroll=function (){

  var aImg=document.getElementsByTagName("img");

  var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;
  var scrollBottom=bodyScrollTop+document.documentElement.clientHeight;
  for (var i=0; i<aImg.length; i++){
    //此时说明这图片已经在可视区域内,应该开始加载了
    if (getFixed(aImg[i])[1]<=scrollBottom){
      aImg[i].src=aImg[i].getAttribute("_src");
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读