我只想要一个简单的切换js,所以当你点击导航中的About时会显示about文本,但它现在正在工作oO
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;
}
我做错了什么?有人能帮助我吗?
答案 0 :(得分: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)
答案 1 :(得分:2)
修复==
问题,然后不使用CSS规则隐藏“about”元素,而是将样式直接放在元素上:
<div id=about style='display: none'>About Me</div>
如果不这样做,JavaScript代码将不会在样式对象上看到“display”属性。 (样式对象仅反映与元素直接关联的样式,而不是CSS样式表控制的样式。)