1. First define the style that needs lazy loading;
Class= "Lazyload"
2. Set the initial transparency to 0.1;
. lazyload{
Filter:alpha (opacity=10); -moz-opacity:0.1; opacity:0.1;
}
3. Place the real address that really needs to be loaded in the DATA-SRC attribute;
src= "lazy loading pictures. png" data-src= "real picture";
4.
Front-end development Zhou Dawei classmate JavaScript code writing:
function Lazyload () {
var lazyload=document.getelementsbyclassname ("Lazyload");
Window.addeventlistener ("Scroll", function () {
SetTimeout (function () {
for (Var i=0;i<lazyload.length;i++) {
var _this=lazyload[i];
var Clientheight=document.documentelement.clientheight | | Document.body.clientHeight;
var Scrolltop=document.documentelement.scrolltop | | Document.body.scrollTop;
if (Clientheight+scrolltop>=offsettop (_this)) {
_this.setattribute ("src", _this.getattribute ("data-src"));
_this.style.opacity= "1";
}
}
},100);
});
}
Get JS code for offsettop and Offsetleft values (compatible)
function OffsetTop (elements) {
var top = Elements.offsettop;
var parent = elements.offsetparent;
while (parent! = NULL) {
Top + = Parent.offsettop;
parent = parent.offsetparent;
};
return top;
};
function Offsetleft (elements) {
var left = Elements.offsetleft;
var parent = elements.offsetparent;
while (parent! = NULL) {
Left + = Parent.offsetleft;
parent = parent.offsetparent;
};
return parent;
};
Native JavaScript code lazy loading