2016-07-07 98 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

相關問題