好的,我有一个带动画的 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 是红色的。
点击时:
- 如果 x 为真,则变为假并且 div 变为蓝色。添加了两个事件监听器,mouseover(div 变为绿色)和 mouseleave(div 再次变为红色)。
- 如果 x 为假,则它变为真并且 div 变为红色。但这是我的问题:两个事件监听器(mouseover 和 mouseleave)都应该被删除,但它不起作用。我在 Internet 上进行了搜索,但没有找到解决我的问题的方法。
有什么帮助吗?
最佳答案
此问题的解决方案是从 dynamicTaskbar()
函数中提取 anim1()
和 anim2()
函数。
由于这两个函数都位于 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>
关于javascript - 无法删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362326/