倍以上的jQuery选择图像(jQuery select images above the fold

2019-09-22 14:34发布

我目前使用jQuery插件lazyload加载图像。 我使用JavaScript来代替src和数据原始属性。 这会导致负载轻微的闪烁。 我想知道是否有与jQuery的方式只选择下方的褶皱或折叠线以上的图像,以便我能避免这种抖动。

var $imgs = $("img:not(.nolazy)");
$imgs.each( function(){
    var imgSrc = $(this).attr("src");
    $(this).attr("data-original",imgSrc).attr("src","gray.gif");
});
$imgs.lazyload({
      effect : "fadeIn"
});

编辑:@Jason Sperske伟大的答案。 这是我已经解决了这个问题,闪烁的代码:

var wH = $(window).height();
var $imgs = $("img:not(.nolazy)");
$imgs.each( function(){
    var imgPosition = $(this).offset();
    if(imgPosition.top > wH){
        var imgSrc = $(this).attr("src");
        $(this).attr("data-original",imgSrc).attr("src","gray.gif");
    }
});
$imgs.lazyload({
      effect : "fadeIn"
});

Answer 1:

While there is no built in selector for this purpose you could iterate over them and look for position values that are greater than the window height. Ben Pickles (his SO profile) has implemented this into a filter called onScreen which you can use like a selector (note that it will still fetch all elements, but then pair down the list before you attempt to modify them, so the selector won't be any faster (actually slightly slower), but the reduced set of elements will be faster to update).



文章来源: jQuery select images above the fold