【问题标题】:How to select element that contains only the class of "foobar", don't select if it contains any other classes?如何选择仅包含“foobar”类的元素,如果它包含任何其他类则不选择?
【发布时间】:2013-11-02 01:09:17
【问题描述】:

我只想选择只有一个类且该类是“foobar”的元素。

<style>
.foobar {
    /* only apply to an element if the element has a class and the only class is 'foobar'. */
    background: black;
    color: white;
}
</style>

<div class="foobar">i should be selected</div>

<div class="foobar ipsum">i should not be selected</div>

我知道我可以通过为 .foobar.ipsum { do one thing } 和 .foobar { something else } 添加样式来选择它,但我无法控制其他类。基本上当元素只有 foobar 类时,我知道它是我的元素并且来自其他地方。这就是 CSS 库世界发生碰撞时发生的情况。我知道这里有更深层次的问题需要解决,但这让我现在很困惑。

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    使用纯 CSS 最简单的方法是使用属性选择器:

    [class="foobar"] {
        /* only apply to an element if the element has a class and the only class is 'foobar'. */
        background: black;
        color: white;
    }
    

    您可能无法控制其他元素,但如果您可以控制自己的元素并且您可以修改其class 属性,mayabelle makes a good point 将您的元素分配给它自己的特殊类并改为由该类选择。这样你就可以明确声明哪个元素是你的,而不是假设没有额外的类就意味着它是你的。

    【讨论】:

    • 这行得通。感谢您并感谢其他提供解决方案的人。我同意@mayabelle 的解决方案,但现在在代码库中找到所有当前元素将是一场噩梦(这是一团糟sigh),所以这个解决方案现在效果最好。
    • @teewuane:是的,这也很好。
    【解决方案2】:

    您需要使用attribute selector

    [class="foobar"] {
        background: black;
    }
    

    http://jsfiddle.net/dA2dp/

    【讨论】:

      【解决方案3】:

      如果它是“你的元素”,你可以为它应用一个额外的类吗?然后你可以选择使用它:

      <style>
      .foobar.yourClass {
          /* your css */
      }
      </style>
      
      <div class="foobar yourClass">i should be selected</div>
      <div class="foobar ipsum">i should not be selected</div>
      

      【讨论】:

      • 我同意你的看法。在这一点上,代码库完全是一团糟,将这个额外的类添加到这些元素中将是一场噩梦。我会解释,但需要一段时间哈哈。所以我将使用上面答案中的属性选择器来解决我手头的问题,而不用担心旧版本的 IE。谢谢!
      猜你喜欢
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2020-05-27
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多