好的,所以我有一个带有动画的div:
var x = true;
function dynamicTaskbar(thumb) {
function anim1() {
thumb.style.backgroundColor = "green";
}
function anim2() {
thumb.style.backgroundColor = "blue";
}
if (x === false) {
thumb.style.backgroundColor = "red";
thumb.removeEventListener("mouseover", anim1);
thumb.removeEventListener("mouseleave", anim2);
x = true;
} else {
thumb.style.backgroundColor = "blue";
thumb.addEventListener("mouseover", anim1);
thumb.addEventListener("mouseleave", anim2);
x = false;
}
}
//Create window's thumbnail for taskbar
var thumbnail = document.createElement("div");
thumbnail.setAttribute("class", "thumbnail");
taskbar.append(thumbnail);
taskbar.style.width = taskbar.style.width + thumbnail.style.width + "px";
thumbnail.addEventListener("mousedown", function() {
dynamicTaskbar(thumbnail);
});
#taskbar {
background-color: red;
border: solid 1px black;
width: 50px;
height: 30px;
}
.thumbnail {
width: 50px;
height: 30px;
border: solid 1px black;
}
<div id="taskbar"></div>
默认情况下,div为红色。
单击时:
有帮助吗?
答案 0 :(得分:1)
此问题的解决方案是从anim1()
函数中提取anim2()
和dynamicTaskbar()
函数。
由于两个函数都位于dynamicTaskbar()
函数内部,因此每次执行该函数时都会一次又一次创建它们,从而导致实例与初始实例不同。
例如,如果在dynamicTaskbar()
的第一次执行(第一次单击)中,anim1()
的“对象ID”将为“ 1”,而在第二次执行中将为“ 2”。因此,当您尝试删除侦听器时,实际上是在尝试将其删除以用于其他对象引用。
看看这个例子:
var x = true;
function anim1(thumb) {
thumbnail.style.backgroundColor = "green";
}
function anim2(thumb) {
thumbnail.style.backgroundColor = "blue";
}
function dynamicTaskbar(thumb) {
if (x === false) {
thumbnail.style.backgroundColor = "red";
thumbnail.removeEventListener("mouseover", anim1);
thumbnail.removeEventListener("mouseleave", anim2);
x = true;
} else {
thumbnail.style.backgroundColor = "blue";
thumbnail.addEventListener("mouseover", anim1);
thumbnail.addEventListener("mouseleave", anim2);
x = false;
}
}
//Create window's thumbnail for taskbar
var thumbnail = document.createElement("div");
thumbnail.setAttribute("class", "thumbnail");
taskbar.append(thumbnail);
taskbar.style.width = taskbar.style.width + thumbnail.style.width + "px";
thumbnail.addEventListener("mousedown", function() {
dynamicTaskbar(thumbnail);
});
#taskbar {
background-color: red;
border: solid 1px black;
width: 50px;
height: 30px;
}
.thumbnail {
width: 50px;
height: 30px;
border: solid 1px black;
}
<div id="taskbar"></div>