JQuery: get elements above given position "y"

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

Apply an attribute z(such as a red background) to each child of the div parent
while their position is above the given top offset y.

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

+3
source share
3 answers

, , - , , , offset , . , :

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

:

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

,

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

,

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

- :

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

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

'#parent > *' ( ) id parent. , , "... div parent".

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

+4

css?

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

Source: https://habr.com/ru/post/1775209/


All Articles