gpt4 book ai didi

javascript - 如何在我的代码中正确使用 mouseleave 函数?

转载 作者:行者123 更新时间:2023-11-30 08:23:47 25 4
gpt4 key购买 nike

好的,所以我需要创建一个带有红色背景的 div,然后注册“Mouseleave”事件,该事件将调用一个函数来显示以下文本“MouseLeave event fired”。我的目标是,当我将鼠标移到我的 div 上然后将其移开时,我会收到一条警告,提示“MouseLeave 事件已触发”。然后,当我再次单击我的 div 时,它将以这种方式注销 MouseLeave 事件,当我将鼠标移到 div 上时,什么也不会发生。这是我到目前为止的代码:

function attachEvent(myObject) {

// to do - get state of listener
myObject.addEventListener("onmouseleave", function attachEvent(){}, false);
alert("Mouse");

// to do - if previously called addEventListener, then I now want to call removeEventListener
myObject.removeEventListener("onmouseleave", function attachEvent(){}, false);

// to do - if previously called removeEventListener, then I now want to call addEventListener
myObject.addEventListener("onmouseleave", function attachEvent(){}, false);
}
div {background-color:red;padding:100px;max-width:25%;margin:auto}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>practice</title>
<script src="scripts.js"></script>
</head>
<body>
<script>
alert("Page loaded event fired");
</script>
<div id="cycle"; onclick="attachEvent(this)">
<h2 style="text-align:center">Click to cycle event listener</h2>
</div>
</body>
</html>

当我将鼠标移出 div 时,警告应该会弹出,但事实并非如此。我究竟做错了什么?请暂时保留这样的代码,因为我还不熟悉 getelementbyid。

最佳答案

  • 您没有正确传递 thisthis 在您的情况下是全局上下文。

  • 要使removeEventListener起作用,回调函数不能是匿名函数。

  • 保留一个标志以检查您是应该添加事件还是删除事件。此标志将在每次点击时切换其值。

  • 使用 mouseleave 而不是 onmouseleave,当您附加的事件内联到元素时使用后一个。

var eventExists = false;

function mouseLeft() {
console.log("Mouse left!");
}

function attachEvent() {
if (!eventExists) {
this.addEventListener("mouseleave", mouseLeft);
} else {
this.removeEventListener("mouseleave", mouseLeft);
}
eventExists = !eventExists;
}
<div style="background-color:red;padding:10px" ; id="cycle" ; onclick="attachEvent.call(this)">
<h2 style="text-align:center">Click to cycle event listener</h2>
</div>

关于javascript - 如何在我的代码中正确使用 mouseleave 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49146131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com