jQuery: get elements above a given 'y' position

强颜欢笑 提交于 2019-12-06 08:25:47

问题


How can you do this with jQuery, in an elegant way?

Apply z attribute (e.g.: red background) to every children of a div parent
while their position is above a given top-offset y.

I've tried in different ways, but I'm not happy with any of them...
I know there must be a short and elegant way to do it...


回答1:


Since you're saying you've tried a few ways, and you're just looking for something more elegant, I'll assume you have the offset part worked out, and I'll just go with offset myself. Modify that part as needed. For elegance, you could create a custom selector checking top offset:

$.expr[':'].above = function(obj, index, meta, stack) { 
    return $(obj).offset().top < meta[3];
}

You could then query it as such:

$('#myParentDiv').find('div:above(100)').css('background-color', 'red');

Of course this could just as well have been expressed as

$('#myParentDiv div:above(100)').css('background-color', 'red');

or, as pointed out in comments

var y = 100;
$('#myParentDiv div:above('+y+')').css('background-color', 'red');



回答2:


Something like this should get the job done:

var y = 250,
    RED = '#F00';

$('#parent > *').css('background-color', function (i, v)
{
    if ($(this).offset().top < y)
    {
        return RED;
    }
    return v;
});

The selector '#parent > *' will select all immediate children (not all descendants) of the element with id parent. I assume that's what you're looking for, since you said "apply... to every children of a div parent."

Demo: http://jsfiddle.net/mattball/87QFU/1/




回答3:


Are the childrens dynamically placed with top-offset or do they all have a common css-class?

 <script type="text/javascript">
   $("div").children(".offsetelement").css("background-color", "red");
 </script>


来源:https://stackoverflow.com/questions/4195620/jquery-get-elements-above-a-given-y-position

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