第一行inline-block div的jQuery选择器 [英] jQuery selector for first row of inline-block divs

查看:119
本文介绍了第一行inline-block div的jQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些div与显示:inline-block;我必须选择第一行div,并设置它们为例如不同的边框颜色,我需要在javaScript(jQuery)。

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).

这里是我的例子上< a href =http://jsfiddle.net/8193xgfn/5/ =nofollow> jsFiddle

HTML:

<div class="container">
    <div class="item">item 1</div>
    <div class="item">item 2</div>
    <div class="item">item 3</div>
    <div class="item">item 4</div>
    <div class="item">item 5</div>
    <div class="item">item 6</div>
    <div class="item">item 7</div>
    <div class="item">item 8</div>
    <div class="item">item 9</div>
</div>

CSS:

.container {
    border: 1px solid red;
    padding: 10px;
}

.item {
    display: inline-block;
    border: 1px solid green;
    width: 200px;
    margin: 10px;
}

有办法吗?

推荐答案

您必须检查第一行中的元素,并标记这些元素。这样做的方法是小提琴

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

此代码假设第一个元素是第一个元素(这总是为真),并检查哪些元素具有相同的偏移顶部,然后对它们应用borderColor更改

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"});   
    }
});

请注意,在现实生活的应用程序中,您可以使用窗口调整大小的事件处理程序来再次运行on window resize。

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

我做了一个单独的小提琴来做事件处理程序版本。这需要在一个函数中包装上面的代码,并改变功能,添加/删除类,而不是只是添加css(因为添加和手动删除css get的凌乱)。 Fiddle可以在这里找到。

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.

因此,添加css,它添加​​/删除一个类

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);

特殊的是改变边框颜色的css类

With special being a css class that changes the border color

.special {
    border-color:purple;
}

这篇关于第一行inline-block div的jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆