In this function, it should give the menu items (li's) an specific background (png) out of an array. However; it doesn't. It gives all the li's the background called color 'blue' :(. Do you see the problem?
//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-开发者_如何学JAVAid-" + (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>
The function you use for onmouseover
is a closuse of the outer function, in the time it is executed all onmouseover
handlers have the save value of i
, to achieve what you seen to want do:
//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();
}
}
}
This surprises me. I would expect it to make all the backgrounds pink. The reason this happens is because by the time you actually hover over any of your <li>
elements, i
will be 10
, and 10 % 4 = 2
. Index #2 of your array is 'pink'
.
To ensure that i
is the value you want when the mouseover and mouseout events are fired, wrap them in a function.
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));
}
}
Here is an explanation that may help: variables-in-anonymous-functions
精彩评论