The approximate implementation method is:
Before the load of the page is triggered, put all the img in the element with the specified ID into imgs, and put the src value of all the pictures into a newly created _src attribute. , set src to the specified display image.
Then, when the scroll event of document.body is triggered, the loop calculates whether the position of the img element in imgs is exactly within the browser display box. If so, the value of the _src attribute of the img element is assigned to src. This way the picture will be displayed.
The more troublesome part here is how to calculate the position of img and obtain the absolute position of the element relative to the page. OffsetLeft and offsetTop are usually used, but these two attributes are the relative position of the element pointed to by the element's offsetParent. If the element pointed by offsetParent is set to float or uses absolute positioning, then offsetLeft is incorrect to obtain the absolute position.
Here I use the sum of the offsetTop of all parent elements of the element to obtain the absolute position of the document.
//Get the absolute X position of the element on the page
var getLeft = function(El){
var left = 0;
do{
BODY' );
return left; do{
top = El.offsetTop; 🎜> When setting the scroll event of the window, IE uses document.documentElement, while other browsers use document.
The next step is to get the current position of the browser display window relative to the document. The following code is used to calculate
Copy code
The code is as follows:
//Read the position of the scroll bar and the display size of the browser window
var top = isGoo? document.body.scrollTop: document.documentElement.scrollTop,
Copy the code
The code is as follows:
//Batch all images to determine whether they are within the browser display area
for(var i=0; i < imgs.length; i){
var _top = getTop(imgs [i]),_left = getLeft(imgs[i]);
> _top <= top height &&
_left <= left width){
var _src = imgs[i].getAttribute('_src');
The picture has been displayed, then cancel the assignment
if (imgs[i].src !== _src){
}
}
Yes Run the code
Copy the code
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn