HTML DOM removeEventListener() 方法
htmlweb developmentfront end technology
DOM removeEventListener() 方法用于从 HTML 文档中的 HTML 元素中移除事件处理程序。
语法
以下是语法 −
document.open(event,function,useCapture);
其中,event 表示事件名称,function 指定要移除的函数,useCapture 可取 true 或 false 值。
其中,true 表示从捕获阶段移除事件处理程序,false 表示从冒泡阶段移除事件处理程序。
示例
让我们看一个 removeEventListener() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-size:1.2rem;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.mycolor{
background-color: #db133a;
}
</style>
</head>
<body>
<h1>DOM removeEventListener() method Demo</h1>
<button class="btn hover-btn">Hover on me</button>
<button onclick="remove()" class="btn">Remove Event Handler</button>
<script>
var hoverBtn=document.querySelector('.hover-btn');
function toggleFun(){
hoverBtn.classList.toggle("mycolor");
}
hoverBtn.addEventListener('mouseover',toggleFun);
function remove(){
hoverBtn.removeEventListener('mouseover',toggleFun);
}
</script>
</body>
</html>
输出
这将产生以下输出 −

将鼠标悬停在"悬停在我身上"按钮上以观察变化,然后点击"移除事件处理程序"按钮,从"悬停在我身上"按钮上移除事件处理程序。

现在,悬停时不会发生任何事情 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

