“document.getElementById onmouseover and function”表现不像×108641

时间:2011-07-01 18:48:11

标签: javascript

在此函数中,它应该为菜单项(li)提供一个特定的背景(png)。然而;它没有。它给所有li的背景称为颜色'蓝色':(。 你看到了问题吗?

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];

function MenuColorChange() {
    for (var i = 0; i <= 10 ; i++) {
        document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() {
        this.style.backgroundImage= "url(images/" +  backgrounds[(i % backgrounds.length)] + ".png)";
        }
        document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
        this.style.background = 'none'; 
        MenuActiveColor();
        }
    }
}

HTML:

        <ul>
            <li id="custom-menu-item-id-1">
                <a href="#">
                    Home
                </a>
            </li>
                            /* And 3 li's more... */
        </ul>

3 个答案:

答案 0 :(得分:2)

用于onmouseover的函数是外部函数的一个闭包,在它执行时所有onmouseover处理程序都具有i的保存值,以实现您所看到的想做的事:

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];
function MenuColorChange() {
    for (var i = 0; i <= 10 ; i++) {
        document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = (function(valueOfI){ return function() {
        this.style.backgroundImage= "url(images/" +  backgrounds[(valueOfI % backgrounds.length)] + ".png)";
        }; })(i);
        document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
        this.style.background = 'none'; 
        MenuActiveColor();
        }
    }
}

答案 1 :(得分:0)

这令我感到惊讶。我希望它可以使所有背景变成粉红色。发生这种情况的原因是,当您实际悬停在任何<li>元素上时,i将为1010 % 4 = 2。数组的索引#2为'pink'

要确保在{em>鼠标悬停和 mouseout 事件被触发时i是您想要的值,请将它们包装在函数中。

function MenuColorChange() {
    for (var i = 0; i <= 10 ; i++) {
        (function(i) {
            document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() {
                this.style.backgroundImage = "url(images/" +  backgrounds[(i % backgrounds.length)] + ".png)";
            }
            document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
                this.style.background = 'none'; 
                MenuActiveColor();
            }
        }(i));
    }
}

答案 2 :(得分:0)

以下是可能有用的说明:variables-in-anonymous-functions