LZ.js
//返回浏览器的可视区域位置 function getClient(){ var l,t,w,h; l = document.documentElement.scrollLeft || document.body.scrollLeft; t = document.documentElement.scrollTop || document.body.scrollTop; w = document.documentElement.clientWidth; h = document.documentElement.clientHeight; return {'left':l,'top':t,'width':w,'height':h} ; } //返回待加载资源位置 function getSubClient(p){ var l = 0,t = 0,w,h; w = p.offsetWidth ; h = p.offsetHeight; while(p.offsetParent){ l += p.offsetLeft ; t += p.offsetTop ; p = p.offsetParent; } return {'left':l,'top':t,'width':w,'height':h } ; } //判断两个矩形是否相交,返回一个布尔值 function intens(rec1,rec2){ var lc1,lc2,tc1,tc2,w1,h1; lc1 = rec1.left + rec1.width / 2; lc2 = rec2.left + rec2.width / 2; tc1 = rec1.top + rec1.height / 2 ; tc2 = rec2.top + rec2.height / 2 ; w1 = (rec1.width + rec2.width) / 2 ; h1 = (rec1.height + rec2.height) / 2; return Math.abs(lc1 - lc2) < w1 && Math.abs(tc1 - tc2) < h1 ; } //比较某个子区域是否呈现在浏览器区域 function jiance(arr,prec1,callback){ var prec2; for(var i = arr.length - 1 ; i >= 0 ;i--){ if(arr[i]){ prec2 = getSubClient(arr[i]); if(intens(prec1,prec2)){ callback(arr[i]); //加载资源后,删除监测 delete arr[i]; } } } } //检测目标对象是否出现在客户区 function autocheck(){ var prec1 = getClient(); jiance(arr, prec1, function(obj) { //加载资源... var desobj = obj; if (desobj.getAttribute("bidsrc") != null && desobj.getAttribute("bidsrc") !="") { desobj.src = desobj.getAttribute("bidsrc"); desobj.style.visibility = "visible"; desobj.setAttribute("bidsrc",""); } }) } //需要按需加载区域集合 var arr ; //子区域一 var d1; function loadLZ() { d1 = document.getElementById("Container"); arr = document.getElementById("Container").getElementsByTagName("img"); } //浏览器客户区尺寸改变后,重新计算 window.onscroll = function() { autocheck(); } window.onresize = function() { autocheck(); } window.onload = function() { loadLZ(); autocheck(); }
------------------------------------------------------------------------------
<html>
<head><script src="lz.js"></script></head>
<body>
<div id="Container" >
<img width="300px" height="300px" bidsrc="img.jpg" /><br />
<img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /> <img width="300px" height="300px" bidsrc="img.jpg" /><br /></div>
</body>
</html>
转载于:https://www.cnblogs.com/caicainiao/archive/2011/11/02/2233092.html
相关资源:lazyload 即时加载图片(鼠标滑动不同页面时,才加载相应图片)