我正在尝试不加载不在视口内的图像。
这就是我做的事情
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
CheckIt();
function CheckIt() {
$('.target').each(function () {
if ($(this).find('img').attr('data-src')) { // if target element exists in DOM
if ($(this).is_on_screen()) { // if target element is visible on screen after DOM loaded
if ($(this).find('img').attr('data-src')) {
var source = $('.target').find('img').attr('data-src');
$('.target').find('img').attr('src', source);
$(this).find('.log').html('<div class="alert alert-success">target element is visible on screen</div>');
}
// log info
} else {
$(this).find('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
}
}
});
}
$(window).scroll(function () { // bind window scroll event
CheckIt();
});
问题的 JSFIDDLE 是here
但不幸的是,视口外的图像也在加载。
任何人都可以告诉我这里的错误