2016-06-10 39 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

已经回答了相同的内容,仍然谢谢你的回答 –