简体   繁体   中英

Trying to load images after scrolling to that area

I am trying to load images after scrolling to that div.There are multiple images in that div but first images is being loaded to every img scr

here is an example:

<div>
   <img src="preload.jpg" data-src="img1.png" data-rel="preload" /> 
   <img src="preload.jpg" data-src="img2.png" data-rel="preload" /> 
   <img src="preload.jpg" data-src="img3.png" data-rel="preload" /> 
   <img src="preload.jpg" data-src="img4.png" data-rel="preload" /> 
   <img src="preload.jpg" data-src="img5.png" data-rel="preload" /> 
</div>

And the jquery i am trying:

function isElementInViewport (el) {

    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}
var imgSet = false;
jQuery(window).on('scroll', function(){
    if(isElementInViewport(jQuery('img[data-rel="preload"]'))){
        var toload = jQuery('img[data-rel="preload"]');
        if(!imgSet){
            toload.each(function(){
                var img = toload.attr('data-src');
                toload.attr('src', img);
                imgSet = true;
            });
        }
    }
});

But problem is that img1.png is being loaded in every src attribute on img

The jquery each function have to take as param the actual item of the iterator, try to change it like this:

jQuery(window).on('scroll', function(){
    if(isElementInViewport(jQuery('img[data-rel="preload"]'))){
        var toload = jQuery('img[data-rel="preload"]');

            toload.each(function(index) {
                if ($(this).visible(true)) {
                   var img = $(this).attr('data-src'); // $(this) is actual image in loop
                   $(this).attr('src', img);
                }
            });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM