Implementation effect: When the scroll bar is pulled, the picture appears in the visible area before it starts loading
Ideas:
(1) img tag, put the real picture address, placed in the properties of their own settings, such as Lazy-src
(2) Get the height of the IMG from the page (in the JQ is offset (). top), native is:
Img.getboundingclientrect (). Top + document.body.scrolltop| | Document.documentElement.scrollTop
(3) Determine whether the location of the IMG appears in the visible area:
,justtop>scrolltop&&offsettop< (scrolltop+windowheight) in the visible area of the browser, where Justtop is the offsettop+ picture height of the picture
Copy Code code as follows:
Save document in a variable, reduce the query to document
var doc = document;
for (var n=0,i = this.oimg.length;n<i;n++) {
Get Picture placeholder picture address
var hsrc = This.oimg[n].getattribute (THIS.SHOLDER_SRC);
if (HSRC) {
var scrolltop = doc.body.scrolltop| | Doc.documentElement.scrollTop,
WindowHeight = Doc.documentElement.clientHeight,
offsettop = This.oimg[n].getboundingclientrect (). Top + scrolltop,
ImgHeight = This.oimg[n].clientheight,
Justtop = offsettop + imgheight;
Determine if the picture is in the visible area
if (justtop>scrolltop&&offsettop< (scrolltop+windowheight)) {
This.isload (Hsrc,n);
}
}
}
The following is the detailed code:
Copy Code code as follows:
function lgy_imgscrollload (option) {
this.oimg = document.getElementById (option.wrapid). getElementsByTagName (' img ');
THIS.SHOLDER_SRC = OPTION.HOLDER_SRC;
This.int ();
}
Lgy_imgscrollload.prototype = {
Loadimg:function () {
Save document in a variable, reduce the query to document
var doc = document;
for (var n=0,i = this.oimg.length;n<i;n++) {
Get Picture placeholder picture address
var hsrc = This.oimg[n].getattribute (THIS.SHOLDER_SRC);
if (HSRC) {
var scrolltop = doc.body.scrolltop| | Doc.documentElement.scrollTop,
WindowHeight = Doc.documentElement.clientHeight,
offsettop = This.oimg[n].getboundingclientrect (). Top + scrolltop,
ImgHeight = This.oimg[n].clientheight,
Justtop = offsettop + imgheight;
Determine if the picture is in the visible area
if (justtop>scrolltop&&offsettop< (scrolltop+windowheight)) {
alert (offsettop);
This.isload (Hsrc,n);
}
}
}
},
Isload:function (src,n) {
var src = src,
n = N,
o_img = new Image (),
_that = this;
O_img.onload = (function (n) {
_that.oimg[n].setattribute (' src ', src);
_that.oimg[n].removeattribute (_THAT.SHOLDER_SRC);
}) (n);
O_IMG.SRC = src;
},
Int:function () {
This.loadimg ();
var _that = this,
timer = null;
Scrolling: Adding timers to prevent frequent calls to loadimg functions
Window.onscroll = function () {
Cleartimeout (timer);
Timer = settimeout (function () {
_that.loadimg ();
},100);
}
}
}
Effect Chart:
The above is the entire content of this article, the implementation of the effect is not better than the implementation of jquery Plug-ins, the code is also concise, small partners to refer to the next bar.