开发者

How to select only elements visible in the window

Using jQuery, I want to change the color of all elements in the current window. The page scrolls, but I don't want ele开发者_JS百科ments scrolled off of the view - which I don't see - to be colored - only the elements in the current view window.


Here is a custom jQuery selector implementing the code from https://stackoverflow.com/a/7557433/128165

$.expr[':'].inViewport = (function(){
    function isElementInViewport (el) {
        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() */
        );
    }

    return function(obj, index, meta, stack){
       return isElementInViewport(obj);
    };
})();

//usage
$(':inViewport').css('color','red'); // color every element fully inside viewport
$('p:inViewport').css('color','red'); // color every paragraph element fully inside viewport


Try ":visible" selector to select only the visible elements

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜