结构如下:
<div id="div1">
<ul>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
<li data-src="http://imgstore.cdn.sogou.com/app/a/100540002/1170479_s_90_2_219x160.jpg"></li>
</ul>
</div>
图片的动态加载就是通过读取li元素,然后获得li元素的data-src属性的值赋予动态创建的图片的src,从而实现了图片的创建。
function setImg(index){
var oDiv=document.getElementById("div1")
var oUl=oDiv.children[0];
var aLi=oUl.children;
if (aLi[index].dataset) {
var src=aLi[index].dataset.src;
} else{
var src=aLi[index].getAttribute('data-src');
}
var oImg=document.createElement('img');
oImg.src=src;
if (aLi[index].children.length==0) {
aLi[index].appendChild(oImg);
}
}
那么怎么识别是否在可视区域呢?这里需要一个函数,能够实现获得当前元素距离网页顶部的距离!
//获得对象距离页面顶端的距离
function getH(obj) {
var h = 0;
while (obj) {
h += obj.offsetTop;
obj = obj.offsetParent;
}
return h;
}
当网页的滚动条滚动时要时时判断当前li的位置!
window.onscroll = function () {
var oDiv = document.getElementById('div1');
var oUl = oDiv.children[0];
var aLi = oUl.children;
for (var i = 0, l = aLi.length; i < l; i++) {
var oLi = aLi[i];
//检查oLi是否在可视区域
var t = document.documentElement.clientHeight + (document.documentElement.scrollTop || document.body.scrollTop);
var h = getH(oLi);
if (h < t) {
setTimeout("setImg(" + i + ")", 500);
}
}
};
当页面加载完成以后要主动运行一下window.onscroll,从而获得当前可视范围内的图片
window.onload = function () {
window.onscroll();
};