开发者

Overflow hidden jQuery Selector

I have several <p> elements inside a <div>. The <div> has overflow-y:auto; which is hiding some <p> elements from view unless you scroll down. See http://jsfiddle.net/qnuxs/1/

How can i write a jQuery selector that only select <p> elements that are fully(not partially) visible and not hidden from view with overflow.

So from the jsfiddle example i provided the selector should give me the first 2 <p>'s (000 and 111) since they are the only tags fully in view.

Note: not all <p> ta开发者_StackOverflow社区gs necessary have the same height. Height can vary.


You can do it, for example using your own .filter() function:

var st = $('div').scrollTop(),
    sh = $('div').height(),
    sb = st + sh - 1;

$('p').css({
    background: '#ccc'
});
$('p').filter(function() {
    var $this = $(this),
        h = $this.height(),
        t = $this.position().top,
        b = t + h - 1;
    return (t >= st && b <= sb);
}).css({
    background: 'red'
});

See DEMO: http://jsfiddle.net/qnuxs/3/

Every five seconds it makes the visible paragraphs red. It waits 5 seconds so you could scroll and see that the remaining paragraphs was not red.

Another DEMO: http://jsfiddle.net/qnuxs/4/

This version updates the colors while you scroll.

Note that the calculations seem to be incorrect so it's few pixels off but it should be enough to get you started. You probably need to use .innerHeight() for the div or maybe change something else but this is the idea: get the scroll position and div height to calculate top and bottom of visible part, and compare those values with top and bottom coordinates (relative to div) of every paragraph, and make your filter select only those within the correct range.


Here's the core of it:

http://jsfiddle.net/qnuxs/5/

Edit: I was going to flesh it out more but rsp beat me too it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜