jQuery selector for first row of inline-block divs

后端 未结 4 1083
生来不讨喜
生来不讨喜 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:03
    $('.item').eq(0).addClass('special-border');
    
    .special-border {
        border-color: #00f;
    }
    

    http://jsfiddle.net/8193xgfn/9/

    0 讨论(0)
  • 2021-02-11 07:10

    You may use vanilla CSS Selector for this in jquery.
    Assuming that you have a grid of 3 X 3.

    $( ".container .item:nth-child(3n + 1)" ).css( "border-color","black" );

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-02-11 07:24

    you can get the width of your container which has a css-style named "container" by $(".container").width,

    and then you can calculate how many divs can be put in the first row,and put it in a variable like firstrow_divNums.

    now use $(".calculate").children() to get the child-divs,

    finally use "for" loop from $(".calculate").children().eq(0) to $(".calculate").children().eq(firstrow_divNums) ,

    and now you can do what you want like adding css-style to any elements.

    0 讨论(0)
提交回复
热议问题