【问题标题】:Changing CSS class with JavaScript has no effect用 JavaScript 改变 CSS 类没有效果
【发布时间】:2011-10-24 07:12:32
【问题描述】:

我希望我的导航栏(以列表的形式)在页面加载时保持不可见(显示:无;),并在单击某些内容时显示(当前使用按钮)

这是我的 HTML 代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<script type="text/javascript" src="js/navbar.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<script type=text/javascript>
function changeClass(){
document.getElementById("mainnav").setAttribute("class", "show");
}
</script>
</head>

<body>

<div class="wrapper">

<input  type="button" value="click" onClick="changeClass()">

<div id="mainnav">

 <ul >
<li>Home</li>
<li>Emergency Repair Service</li>
<li>Heating</li>
<li>Air Conditioning</li>
<li>Products</li>
<li>Specials</li>
<li>Contact</li>
</ul>

</div><!--mainnav-->

这是我的 CSS

#mainnav {
display:none;
}

ul li {
float: left;
list-style-type: none;
}

.show {
display: block;
height: 75px;
width: 100%;
background-color: #000;
}

这是我的 javascript

function changeClass(){
document.getElementById("mainnav").setAttribute("class", "show");
}

谢谢!

【问题讨论】:

    标签: html css setattribute


    【解决方案1】:

    我觉得 js 不错,但是 css 有问题,试着改成下面这样。

    .show {
    display: block !important;
    height: 75px;
    width: 100%;
    background-color: #000;
    }
    

    【讨论】:

      【解决方案2】:

      它有效。在此处查看我的示例:http://jsbin.com/uyonuc

      您确定将其设置为最初对 CSS 隐藏吗?

      还可以尝试将!important 添加到display:block 以确保它覆盖任何其他属性。

      【讨论】:

        【解决方案3】:

        ID 选择器 (#mainnav) 规则的优先级高于类选择器 (.show) 规则。因此,display:none 将持续存在,即使您为 div 分配了 .show 类。

        您最初可以使用 .hide 类并将其替换为 .show 或在 CSS 中使用 !important 规则。

        一篇关于 CSS 特异性的文章:http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

        【讨论】:

          【解决方案4】:

          改变这个:

          .show {
              display: block;
              height: 75px;
              width: 100%;
              background-color: #000;
          }
          

          到这里:

          #mainnav.show {
              display: block;
              height: 75px;
              width: 100%;
              background-color: #000;
          }
          

          .show 类中的display:block 将覆盖#mainnav 选择器中的display:none,因为新规则更具体。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-06-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-12
            • 1970-01-01
            相关资源
            最近更新 更多