我正在尝试了解如何使用循环和document.getElementtById一起在多个跨度上创建鼠标悬停事件并更改ID。我应该使用document.getElementByTagName而不使用循环(只使用'span'标签)吗?
这是html:
<span id="test1">really</span>
<span id="test2">really</span>
<span id="test3">really</span>
<span id="test4">bad</span>
这是我的javaScript:
var myspan = document.getElementById("test" + i);
for (var i = 0; i < myspan.length; i++) {
test.addEventListener("mouseenter", function( event ) {
event.target.style.color = "purple";
setTimeout(function() {
event.target.style.color = "";
}, 5000);
}, false);
}
答案 0 :(得分:0)
var myspan = document.getElementsByTagName("span");
for (var i = 0; i < myspan.length; i++) {
myspan[i].addEventListener("mouseenter", function(event) {
this.style.color = "green";
setTimeout(function() {
this.style.color = "";
}.bind(this), 1000);
}, false);
}
在上面的代码段中,我更改了您的代码。我个人更喜欢使用CSS,或以下代码
[].forEach.call(document.querySelectorAll("span"), function(elem) {
elem.onmouseover = function() {
elem.style.color = "green";
setTimeout(function() {
elem.style.color = "";
}, 1000)
}
});