2

我只想要一个简单的切换 js,所以当您在导航中单击 About 时,会出现 about 文本,但它现在可以正常工作了

JS部分:

<script language="JavaScript" type="text/javascript">
function toggle() {
var about = document.getElementById('about')
if(about.style.display = "none")
{
about.style.display = "block";
}

else
{
about.style.display = "none";
}
}
</script>

HTML:

<header>
...
    <nav><ul>
        <li><a href="index.html" id="active">Home</a></li>
        <li><a href="javascript:toggle()" onClick="toggle()">About me</a></li>
        ...more <li>s...
    </ul></nav>
</header>
<br/>

<div id="about">
aboutme
</div>

CSS:

#about {
    display: none;
    }

我究竟做错了什么??有谁能够帮助我?

4

2 回答 2

5

在 if 语句中,您必须have two equal sign

function toggle() {
    var about = document.getElementById('about');
    if(about.style.display == "none")
    {
        about.style.display = "block";
    }
    else
    {
        about.style.display = "none";
    }
}

笔记

= you can just assign value to variable
== must be used to compare variables values
=== must be used to compare variables in every aspect (In type too)
于 2013-01-13T15:21:52.217 回答
2

修复==问题,然后不要使用该 CSS 规则隐藏“about”元素,而是将样式直接放在元素上:

<div id=about style='display: none'>About Me</div>

如果您不这样做,JavaScript 代码将看不到样式对象上的“显示”属性。(样式对象仅反映与元素直接关联的样式,而不是由 CSS 样式表控制的样式。)

于 2013-01-13T15:25:10.750 回答