我正在尝试在滚动到该div后加载图像。该div中有多个图像,但第一个图像正在加载到每个img scr
这是一个例子:
<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>
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;
});
}
}
});
但问题是img1.png
src
属性都加载了img
答案 0 :(得分:0)
每个函数必须将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);
}
});
}
});