Overflow hidden jQuery Selector

ε祈祈猫儿з 提交于 2019-12-11 02:06:10

问题


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> tags necessary have the same height. Height can vary.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5287425/overflow-hidden-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!