学习要点:
1.问题所在
2.设置代码
本节课,我们将编写一个图片加载的功能:延迟加载和预加载;顾名思义,延迟就是推
后加载,预加载就是提前加载的意思。
一.问题所在
QQ截图20190518093311.pngHTML 代码
<div id="photo">
<dl>
<dt><img xsrc="images/p1.jpg" src="images/wait_load.jpg" class="wait_load" /></dt>
<dd>延迟加载图片</dd>
</dl>
<dl>
<img xsrc="images/p2.jpg" src="images/wait_load.jpg" class="wait_load" />
<dd>延迟加载图片</dd>
</dl>
<dl>
<img xsrc="images/p3.jpg" src="images/wait_load.jpg" class="wait_load" />
<dd>延迟加载图片</dd>
</dl>
CSS 代码
#photo {
width:900px;
float:left;
}
#photo dl {
width:225px;
height:270px;
float:left;
margin:5px 0 15px 0;
}
#photo dl dt {
width:200px;
height:250px;
background:#eee;
margin:0 auto;
}
#photo dl dt img {
display:block;
width:200px;
height:250px;
cursor:pointer;
}
#photo dl dd {
height:25px;
line-height:25px;
text-align:center;
}
JS 代码
//图片延迟加载
var wait_load = $('.wait_load');
wait_load.opacity(0);
$(window).bind('scroll', function () {
setTimeout(function () {
for (var i = 0; i < wait_load.length(); i ++) {
var _this = wait_load.ge(i);
if ((getInner().height + getScroll().top) >= offsetTop(_this)) {
$(_this).attr('src', $(_this).attr('xsrc')).animate({
attr : 'o',
target : 100,
t : 30,
step : 10
});
}
}
}, 100);
});
//获取元素到顶点的距离
function offsetTop(element) {
var top = element.offsetTop;
var parent = element.offsetParent;
while (parent !== null) {
top += parent.offsetTop;
parent = parent.offsetParent;
}
return top;
}
//获取或设置属性
Base.prototype.attr = function (attr, value) {
for (var i = 0; i < this.elements.length; i ++) {
if (arguments.length == 1) {
return this.elements[i].getAttribute(attr);
} else if (arguments.length == 2) {
this.elements[i].setAttribute(attr ,value);
}
}
return this;
};
网友评论