在我的文件的 HTML 中,我有一个 ID 为“divNavyBox”的 div。代码如下。
<div id="divNavyBox" class="box" onmouseover="animated.doAnimation()"></div>
请注意,一旦鼠标悬停在其上,它就会执行 varanimated 中的 doAnimation()。
var animated = {
el : document.getElementById("divNavyBox"),
doAnimation : function() {
if (el.className=="box") {
el.className="boxAlt";
}
if (el.className=="boxAlt") {
el.className="box";
}
}
};
我希望它在执行 doAnimation 方法后在这两个 cs 类之间切换。然而,它没有做任何事情。我在 if(el.className="box"中放置了一条警报语句,并且在执行该函数时它没有响铃,即使该类确实是盒子。列出了我想要使用的两个 CS 类如下:
.box {
width: 100px;
height: 100px;
background-color: navy;
}
.boxAlt {
width: 100px;
height: 100px;
background-color: red;
}
为什么 bool 语句 el.className="box"总是返回 false?
最佳答案
如果当前 = box,则在此处分配 boxAlt
if (el.className=="box") {
el.className="boxAlt";
}
如果当前是 boxAlt,则在此处切换回来如果该类从一开始就是 box,则始终为 true。
if (el.className=="boxAlt") {
el.className="box";
}
将其更改为:
doAnimation : function() {
el.className = el.className == "box" ? "boxAlt" : "box";
}
关于javascript - 为什么 Javascript 无法访问该 html 元素的类信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6289285/