jQuery selector for first row of inline-block divs

后端 未结 4 1152
生来不讨喜
生来不讨喜 2021-02-11 06:24

I have some divs with display: inline-block; and I have to select first row of divs and set them for example different border color and I need to do it in javaScript (jQuery).

4条回答
  •  没有蜡笔的小新
    2021-02-11 07:15

    You have to check what elements are in the first row, and mark those. A way to do this would be fiddle

    This code makes the assumption that the first element is first in a row (which is always true), and checks which elements have the same offset top, it then applies a borderColor change to them

    var top;
    $('.container .item').each(function(i){
        var thistop = $(this).offset().top;
        if (i==0){
            top = thistop;
        }
        if (top==thistop){
            $(this).css({borderColor:"purple"});   
        }
    });
    

    Note that in a real life application you'd use a event handler on window resize to run this again on window resize.

    I made a separate fiddle to do the event handler version. This requires wrapping above code in a function, and changing the functionality a bit to add/remove classes instead of just adding css (since adding and manually removing css get's messy). Fiddle can be found here.

    So instead of adding css, it adds/removes a class

    markrow = function(){
            $('.container .item').each(function(i){
            ...
            if (top==thistop){
                $(this).addClass('special');
            }else{
                $(this).removeClass('special');
            }
        });
    }
    markrow();
    $(window).on('resize',markrow);
    

    With special being a css class that changes the border color

    .special {
        border-color:purple;
    }
    

提交回复
热议问题