当ID由默认类设置时,通过Javascript更改CSS类

时间:2015-04-11 19:09:13

标签: javascript css

我有一个DIV,它通过ID在外部样式表中应用了CSS,例如:

<div id="myFavoriteDIVever">Stuff</div>

#myFavoriteDIVever {
    display: none;
}

然后,在Javascript函数中,我将以下类设置为相同的DIV:

document.getElementById('myFavoriteDIVever').className = 'superCoolClass';

.superCoolClass {
    display: block;
}

出于某种原因,当我这样做时,DIV不会设置为显示为块。它仍未显示在DOM中。但是如果我改变它,那么DIV应用了一个默认的CSS类来设置display:none;然后我用Javascript设置一个不同的CSS类来设置display:block;它按预期工作,并将DIV显示为块元素。

为什么CSS类会覆盖ID CSS?因此,当我应用新的className时,它应该覆盖#element设置。否?

4 个答案:

答案 0 :(得分:2)

Ids具有更高的优先级,因此添加类不会产生任何影响。你最好的镜头是:

<div id="myFavoriteDIVever" class="myFavoriteDIVever">Stuff</div>

.myFavoriteDIVever {
    display: none;
}
document.getElementById('myFavoriteDIVever').className = 'superCoolClass';

答案 1 :(得分:2)

Ascending order of specificity

  

以下选择者列表是通过提高特异性来实现的:

     
      
  • 环球
  •   
  • 选择器类型
  •   
  • 选择器类
  •   
  • 选择器属性
  •   
  • 选择器伪类
  •   
  • ID选择器
  •   
  • 内联样式
  •   

您可以使用内联样式覆盖它

document.getElementById('myFavoriteDIVever').style.display = 'block';
#myFavoriteDIVever {
    display: none;
    width: 300px;
    height: 400px;
    background: red
}
<div id="myFavoriteDIVever" class="myFavoriteDIVever">Stuff</div>

答案 2 :(得分:1)

问题不在于你的javascript,它与CSS有关。有一个称为特异性的概念。这个想法是每个CSS条目都有一些特定值(1000,100,10,1)。将应用的样式是最“特定”的样式。 ID选择器= 100.类选择器= 10.ID将获胜。尝试从

更改课程的CSS
  

.superCoolClass { display: block; }

  

#myFavoriteDIVever.superCoolClass { display: block; }

答案 3 :(得分:0)

这应该没问题:

HTML:

<div id="myFavoriteDIVever">Stuff</div>

CSS:

#myFavoriteDIVever {
    display: none;
}

#myFavoriteDIVever.show {
    display: block;
}

JS:

document.getElementById('myFavoriteDIVever').className = 'show';