如何检查移动浏览器视口中可见的所有元素

时间:2014-09-24 07:36:32

标签: javascript jquery css jquery-mobile viewport

我正在尝试检查包含图像的div是否在视口中。

我尝试了以下代码

$.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

谢谢&amp;问候

0 个答案:

没有答案