jQuery: get elements above a given 'y' pos

2019-04-12 00:42发布

问题:

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>