2016-06-10 79 views
0

得到混淆有關類的優先級在CSS中,我知道在最後添加的類具有最高優先級,但在這裏我的例子 我以爲我錯了我動態地添加類div,但類不能正常工作Css類的優先級,當添加動態類

<p>Click the button to add the "mystyle" class to DIV.</p> 

<script> 
    function myFunction() { 
    document.getElementById("myDIV").classList.add("mystyle","hello"); 
} 
</script> 

<style> 
.hello{ 
background-color: blue; 
} 
.mystyle { 
    background-color: red; 
} 
</style> 

爲什麼div顯示紅色而不是藍色?

Working Example

+0

可能的重複http://stackoverflow.com/questions/17727739/precedence-of-multiple-classes-defining-color-property-being-set-by-claclaration – Harry

+0

你回答自己的問題:'class added at **最後**具有**最高優先級**' - 您的最後一個類是'.myStyle',所以... – somethinghere

+0

我的意思是說在使用類名時這樣的'

'@somethinghere –

回答

5

div是紅色的,而不是藍色的,因爲你的風格聲明順序:

.hello { 
    background-color: blue; 
} 

.mystyle { 
    background-color: red; 
} 

CSS特異性不依賴於你應用類元素的順序,而是您在樣式中聲明類的順序。在這種情況下,您已宣佈.hello,然後.mystyle,這意味着.mystyle.hello相比具有較高的特異性,因此您會得到紅色背景。

+0

很好的答案,你認爲HTML中定義的類的順序與它們的重要性無關。我錯過了! – somethinghere

+0

很好的答案,這意味着HTML中類的聲明無關緊要嗎?你可以提供任何鏈接提到這一切嗎? –

+0

有沒有真正的鏈接反駁這一點,但首先閱讀CSS選擇器(https://developer.mozilla.org/en/docs/Web/Guide/CSS/Getting_started/Selectors),並牢記在心該CSS是將定義佈局的文檔。原因是它解耦了你的代碼 - 所以如果你想在未來讓其他類更加突出,你只需要改變你的CSS文件,而不是JS在任何地方或者HTML聲明它的地方。 – somethinghere

1

這是層次的問題:

function myFunction() { 
 
    document.getElementById("myDIV").classList.add("mystyle","hello", "red-background"); 
 
}
#myDIV.hello{ 
 
background-color: blue; 
 
} 
 
.mystyle { 
 
    background-color: red; 
 
} 
 
.mystyle { 
 
    width: 300px; 
 
    height: 50px; 
 
    background-color: red; 
 
    color: white; 
 
    font-size: 25px; 
 
}
<p>Click the button to add the "mystyle" class to DIV.</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p> 
 

 
<div id="myDIV"> 
 
I am a DIV element 
 
</div>

+0

在上面的註釋中用@somethinghere表示'HTML中類的聲明與它們的重要性無關,或者它們被添加時,它們都是基於CSS中的規則評估的,而不是HTML中的規則,而不是爲什麼您的div顯示爲藍色res,因爲紅色是在css中藍色後定義的?這裏發生了什麼 ? –

+0

我做了一個小提琴,在這裏你可以找到所有的解釋:https://fiddle.jshell.net/zd8mzxg3/4/ –

1

因爲在翻譯讀第一類.hello那麼類.mystyle ... 該div有兩個類......當你的類已添加.mystyle類的優先級從.hello ...

<style> 
    .mystyle { 
     background-color: red; 
    } 
    .hello{ 
     background-color: blue; 
    } 

</style> 

here you can see working example

+0

已經回答了相同的內容,仍然謝謝你的回答 –