开发者

Why is the class information for this html element not accessed by Javascript?

In my HTML for my file I have a div with the id "divNavyBox." The code is below.

<div id="divNavyBox" class="box" onmouseover="animated.doAnimation()"></div>

Note that once the mouse hovers over it, it executes the doAnimation() from var animated.

var animated = {

el : document.getElementById("divNavyBox"),

doAnimation : function() {
    if (el.className=="box") {

        el.className="boxAlt";
    }
    if (el.className=="boxAlt") {
        el.className="box";
    }

}

};  

I want it to switch between these two cs classes once the method doAnimation is executed. However, it doesn't do 开发者_如何学编程anything. I put an alert statement inside of the if(el.className="box" and it didn't ring up as I executed the function, even though the class really IS box. The two CS classes that I want to be used are listed below:

.box {

    width: 100px;

    height: 100px;

    background-color: navy;

}
.boxAlt {
width: 100px;
height: 100px;  
background-color: red;
}

Why does the boolean statement el.className="box" keep returning false?


here you assign boxAlt if current = box

if (el.className=="box") {
    el.className="boxAlt";
}

here you switch back if current is boxAlt which is allways true if the class has been box from the beginning.

if (el.className=="boxAlt") {
    el.className="box";
}

Change it to something like:

doAnimation : function() {
    el.className = el.className == "box" ? "boxAlt" : "box";
}


There are at least three problems with your code:

I wonder why there is a ; before onmouseover.

Then you use el.className="box" in the if() which assigns "box" to className. Use == to compare.

Lastly, el.style.className is undefined.


el.className = "box" is not a Boolean statement, it's an assignment.

el.className == "box" is a boolean statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜