【问题标题】:nth-child except if it has a class of "hide"nth-child 除非它有一个“隐藏”类
【发布时间】:2012-10-26 13:02:22
【问题描述】:

我有几个左浮动的项目 div,因此它们看起来在列中。用户可以单击任何给定项目上的“隐藏”,并为该元素添加一个“.hide”类,该元素具有 display:none css。

问题:有没有办法做到.item:not(.hide):nth-child(2n+2)?因此,当我有一个项目列表,其中一个项目的中间有 .hide 时,该规则仍然适用并“忽略”.hide 项目。

jsbin 中的实例,http://jsbin.com/ajeqal/edit#javascript,html,live

如果您在右侧列项中单击“隐藏”,则列会出现乱序,因为左侧列应该始终具有与右侧列不同的背景颜色。我可以将隐藏的项目移到列表的末尾,但这需要更多的工作。

HTML:

<style>
  .hide { display:none;}
  .item{ float: left; width: 150px; padding: 5px; background: #ccc;}
  .item:not(.hide):nth-child(2n+1) { background: #999; margin-right:5px }
  .item a { display:inline-block; margin-left: 10px; }
  body { width: 325px; }
  #unhideAll { display: none; clear: left; margin-top: 20px;}
  #container { overflow: auto; }
</style>
<body>
  <div id="container">
  <div class="item">item<a href="#">hide</a></div>
  <div class="item">item<a href="#">hide</a></div>
  <div class="item hide">item<a href="#">hide</a></div>
  <div class="item">item<a href="#">hide</a></div>
  </div>
  <div id="unhideAll"><a href="#">Unhide All</a></div>
</body>

Js:

$('#unhideAll').click(function(e) {
  e.preventDefault();
  $(".hide").removeClass("hide");
  $(this).hide();
});

$(".item a").click(function(e) {
  e.preventDefault();
  $(this).parent().addClass("hide");
  $("#unhideAll").show();
});

【问题讨论】:

  • $('.item:nth-child(2n+2)').not($('.hide'))
  • 谢谢,但我希望在 CSS 中有一个规则来为我做这件事
  • 不幸的是,没有这样的规则。 CSS :nth-child() 不会这样过滤。
  • 没有。 nth-child 不与其他选择器结合使用..

标签: jquery css pseudo-class


【解决方案1】:

没有 css 选择器可以做到这一点。相反,我必须获取所有“.hide”元素并附加到包含所有这些元素的 div,基本上将它们全部移到最后。如果我这样做,那么它们将不再与其他项目相互混合。

【讨论】:

    【解决方案2】:

    在处理组的过滤选择时,Nth-child 可能会违反直觉。

    使用 .each() 绕过它的限制:

    var count = 0;
    $('.item:not(.hide)').each(function(){
        if ( count++ % 2 == 1 ) $(this).css('background-color','#999')
    })
    

    【讨论】:

      【解决方案3】:

      首先,你可以说 nth-child(odd)。

      其次,如果你想试一试,你可以尝试添加一个 notHidden 类(最初都会有),当添加 'hide' 时删除 'notHidden' ,反之亦然。然后你可以在 .notHidden 上 nth-child(理论上)。

      正如其他人所说,您当前的操作方式将不起作用,因为 nth-child 不认为它已被删除,我不确定这是否会起作用,但如果没有的话,它可能会给您一个想法否则。

      【讨论】:

        【解决方案4】:

        你试过.item:not(.hide):nth-of-type(2n+2)吗?我打算做一些测试来确认,但乍一看,它似乎可行。

        【讨论】:

        • 回复我自己的建议:不,不,它不起作用。显然,元素名称在 :not() 限定符之前匹配,因此您选择元素本身,然后一些元素是否隐藏。诅咒!
        猜你喜欢
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 2013-04-04
        • 2017-08-11
        • 2016-03-29
        • 2012-03-14
        • 2016-02-20
        • 1970-01-01
        相关资源
        最近更新 更多