【问题标题】:Select every first unique element by grouping通过分组选择每个第一个唯一元素
【发布时间】:2017-09-28 03:06:33
【问题描述】:

我有一个具有交替类的元素列表。类的出现是随机的,可以连续出现一次或多次。

我正在寻找一种方法来选择每个第一次出现的元素(标有-)。最好,我想在 CSS 中执行此操作,但我也可以使用 JavaScript 解决方案。

<div class="type-1"></div>  -
<div class="type-1"></div>
<div class="type-1"></div>
<div class="type-2"></div>  -
<div class="type-1"></div>  -
<div class="type-1"></div>
<div class="type-2"></div>  -
<div class="type-2"></div>
<div class="type-1"></div>  -
...

【问题讨论】:

    标签: javascript css css-selectors


    【解决方案1】:

    就像这样:https://jsfiddle.net/aq8nw21f/

    此代码使用 CSS 相邻兄弟选择器以及 :first-of-type 来获取列表中第一项的边缘情况。

    #container > div:first-of-type, .type-1 + .type-2, .type-2 + .type-1 {
      color: red;
    }
    <div id="container">
        <span>If you used :first-child, the div below this would not highlight.</span>
        <div class="type-1">Yes</div>
        <div class="type-1">No</div>
        <div class="type-1">No</div>
        <div class="type-2">Yes</div>
        <div class="type-1">Yes</div>
        <div class="type-1">No</div>
        <div class="type-2">Yes</div>
        <div class="type-2">No</div>
        <div class="type-1">Yes</div>
    </div>

    【讨论】:

    • @insertusernamehere 请不要对其他人的代码进行纯粹的风格编辑,尤其是当这些编辑损害可读性时
    • 你不需要第一个类型,只需自动标记第一个元素。
    • 实际上,:first-child 会假设第一个 div 是其父容器中的第一个子元素。我们不能做出这样的假设,所以:first-of-type 更合适。
    • @Sebastien,只有小提琴中的相邻兄弟选择器(+)按预期工作。请参阅我上面的评论。您的复合类和 :first-of-type 选择器没有做太多:jsfiddle.net/rep7ctza/2
    • @Michael_B 关于无法使用类是正确的。它似乎可以工作,即使它不应该有,但我还是改变了它。
    【解决方案2】:

    还有一个比 TW80000 的 CSS 更不引人注目的 JS 解决方案:

    var els = Array.from(document.querySelectorAll('div[class^="type-"]'));
    
    console.log(els.filter(function(el, index) {
      return index === 0 || !el.classList.contains(els[index - 1].classList.item(0));
    }));
    <div class="type-1">1</div>
    <div class="type-1">2</div>
    <div class="type-1">3</div>
    <div class="type-2">4</div>
    <div class="type-1">5</div>
    <div class="type-1">6</div>
    <div class="type-2">7</div>
    <div class="type-2">8</div>
    <div class="type-1">9</div>

    【讨论】:

    • 很酷的解决方案,但是鼓励 JS 解决方案来解决 CSS 中的问题似乎是相当糟糕的做法,除非这解决了某种跨浏览器兼容性问题? :)
    • 它没有。 CSS 解决方案要好得多。我能想到的唯一用途是CSS实际上不能做的那些,例如向节点添加内容或事件处理程序等......
    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多