我正在尝试在单击Canvas元素时删除eventListener:
document.getElementById("canvas")
.addEventListener("click", setPath, false);
function setPath() {
if (check) {
document.getElementById("canvas").
addEventListener("mousemove", mouseOverPath, false);
} else {
document.getElementById("canvas").
removeEventListener("mousemove", mouseOverPath, false);
}
function mouseOverPath(event) {
drawLine.x = event.clientX;
drawLine.y = event.clientY;
drawLine.draw();
}
}
document.getElementById("canvas").
addEventListener("click", () => {
if (check == true) {
check = false;
} else if (check == false) {
check = true;
}
}, false);Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" height="200" width="200" style="border:1px solid black;">Run Code Online (Sandbox Code Playgroud)
if语句正确执行但removeEventListener不正确.
检查部分:
你的问题是你定义mouseOverPath在setPath:
function setPath() {
if (check) {
document.getElementById("canvas").addEventListener("mousemove", mouseOverPath, false);
} else {
document.getElementById("canvas").removeEventListener("mousemove", mouseOverPath, false);
}
function mouseOverPath(event) {
drawLine.x = event.clientX;
drawLine.y = event.clientY;
drawLine.draw();
}
}Run Code Online (Sandbox Code Playgroud)
对于每个电话setPath的mouseOverPath是一个不同的对象,所以 mouseOverPath 对于addEventListener和一个用于removeEventListener指代不同的对象,并作为该removeEventListener什么都不做.
mouseOverPath如果setPath 函数你需要移出函数.
这是一个简化的问题测试案例:
var tmp;
function test() {
if (!tmp) {
// save the current foo for the first call of test
tmp = foo
} else {
// the comparison of the current foo with tmp (the previous foo) is false
console.log(tmp == foo)
}
function foo() {}
}
test()
test()Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |