简体   繁体   English

滚动到该区域后尝试加载图像

[英]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 我正在尝试在滚动到该div后加载图像。该div中有多个图像,但是第一个图像正在加载到每个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: 我正在尝试的jQuery:

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 但是问题是img1.png被加载到img每个src属性中

The jquery each function have to take as param the actual item of the iterator, try to change it like this: jQuery每个函数都必须将迭代器的实际项目作为参数,尝试像这样更改它:

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);
                }
            });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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