2016-07-07 96 views
4

我想使用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>

+0

难道没有的jQuery也意味着没有普通的JavaScript? – Damon

+0

属性!=类型。 – CBroe

回答

5

不幸的是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>

-1

我从来没有意识到第一的类型没有数据的属性区分!你可以做这样的事情,如果它显示为第一项,或者如果有任何没有data-result = invalid的P标签,它会得到它。

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

当在其中添加其他元素时,不会出现错误。 [1](https://jsfiddle.net/j869utL7/1/)你可以做什么,是泛化'not'选择器像[2](https://jsfiddle.net/j869utL7/2/),但它是清楚地表明这不太合适。 (没有p标签选择器,太普通的选择器,星号选择器永远不是一个好的开始。) –

+0

你说得对 - 我认为你的解决方案是最好的方法! – will

相关问题