【问题标题】:Select first element with data attribute [duplicate]选择具有数据属性的第一个元素[重复]
【发布时间】:2016-11-10 02:13:48
【问题描述】:

我想使用 css 选择包含属性 data-result="INVALID" 的段落 <p> 的第一个匹配项。

我试过这个小脚本没有任何成功。没有元素被选中。

我仅限于这个解决方案的 css(没有 jQuery)。这个问题有解决办法吗?

p[data-result="INVALID"]:first-of-type {
  color: red;
}
<p data-result="VALID"><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be effective.</p>


<p data-result="INVALID"><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p>
<p data-result="INVALID"><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p>

【问题讨论】:

  • 没有 jQuery 是否也意味着没有普通的 javascript?
  • 属性 != 类型。

标签: html css css-selectors


【解决方案1】:

很遗憾,CSS 没有过滤器选择器,例如 p[data-result="INVALID"]:firstp[data-result="INVALID"]:first-with-attribute。您可以通过首先将所有相应项目设置为红色来模仿您想要的行为,然后将作为相同项目的下一个兄弟的所有项目反转回黑色。

我还想向您指出我在代码中遇到的两个问题:使用大写的类名、ID、属性和你所拥有的东西是令人困惑的。要么全部使用小写,要么全部使用大写。有些人(尤其是后端开发人员)喜欢使用驼峰式,但我不喜欢它——尽管这是个人的。但为了统一性和可管理性,建议坚持一种约定,不要开始混淆。其次,b 标签可能不是您想要的。它曾经是一个非常方便的标签,但后来在许多方面都被strong 标签所超越。详情见以下链接:

p[data-result="INVALID"] {
  color: red
}

p[data-result="INVALID"] ~ p[data-result="INVALID"] {
    color: black;
}
<p data-result="VALID"><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be effective.</p>
<p data-result="INVALID"><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p>
<p data-result="INVALID"><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p>

【讨论】:

    【解决方案2】:

    我从来没有意识到 first-of-type 并没有区分数据属性!你可以做这样的事情,如果它显示为第一个项目,或者如果有任何 P 标签没有 data-result=invalid 在它之前。

    p[data-result="INVALID"]:first-of-type, p:not([data-result="INVALID"]) + p[data-result="INVALID"]{
      styles here
    }
    

    【讨论】:

    • 当在中间添加其他元素时,这不会起作用。 1 你可以做的是推广not 选择器,就像2 一样,但很明显这也不太合适。 (没有 p-tag 选择器,太笼统的选择器,星号选择器永远不是一个好的开始。)
    • 你是对的 - 我认为你的解决方案将是最好的方法!
    猜你喜欢
    • 2015-06-07
    • 2014-06-10
    • 2018-05-20
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多