为什么Javascript不能访问这个html元素的类信息?
在我的HTML文件中,我有一个id为“divNavyBox”的div为什么Javascript不能访问这个html元素的类信息?,javascript,Javascript,在我的HTML文件中,我有一个id为“divNavyBox”的div <div id="divNavyBox" class="box" onmouseover="animated.doAnimation()"></div> 我希望它在执行方法doAnimation后在这两个cs类之间切换。然而,它什么也不做。我在if(el.className=“box”中放了一个警报语句,在我执行函数时,它没有响起来,即使该类实际上是box。下面列出了我想要使用的两个CS类: .box
<div id="divNavyBox" class="box" onmouseover="animated.doAnimation()"></div>
我希望它在执行方法doAnimation后在这两个cs类之间切换。然而,它什么也不做。我在if(el.className=“box”中放了一个警报语句,在我执行函数时,它没有响起来,即使该类实际上是box。下面列出了我想要使用的两个CS类:
.box {
width: 100px;
height: 100px;
background-color: navy;
}
.boxAlt {
width: 100px;
height: 100px;
background-color: red;
}
为什么布尔语句el.className=“box”总是返回false?el.className=“box”
不是布尔语句,而是赋值
el.className==“box”
是一个布尔语句。您的代码至少有三个问题:
我想知道为什么在mouseover之前有一个;
然后在if()
中使用el.className=“box”
,将“box”
分配给className
。使用==
进行比较
最后,
el.style.className
是未定义的。如果当前=框
if (el.className=="box") {
el.className="boxAlt";
}
在这里,如果当前值为boxAlt,则切换回原来的值,如果类从一开始就是box,则始终如此
if (el.className=="boxAlt") {
el.className="box";
}
将其更改为:
doAnimation : function() {
el.className = el.className == "box" ? "boxAlt" : "box";
}
谢谢你的建议。我修复了这三个问题,现在它们被放到了原来的帖子中。即使我修复了这三个问题,doAnimation函数仍然不会改变divNavyBox的类。添加
alert(typeof el)
作为doAnimation
中的第一个命令。它可能是未定义的
doAnimation : function() {
el.className = el.className == "box" ? "boxAlt" : "box";
}