<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
}
</style>
</head>
<body>
<p>Internet Explorer 8 及更早版本不支持 removeEventListener() 方法。</p>
<p>此示例演示了适用于所有浏览器的解决方案。</p>
<div id="myDIV">这个 div 元素有一个 onmousemove 事件处理程序,它会在您每次将鼠标移到这个橙色字段内时显示一个随机数。
<p>单击按钮删除 DIV 的事件处理程序。</p>
<button onclick="removeHandler()" id="myBtn">试一试</button>
</div>
<p id="demo"></p>
<script>
var x = document.getElementById("myDIV");
if (x.addEventListener) {
x.addEventListener("mousemove", myFunction);
} else if (x.attachEvent) {
x.attachEvent("onmousemove", myFunction);
}
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
if (x.removeEventListener) {
x.removeEventListener("mousemove", myFunction);
} else if (x.detachEvent) {
x.detachEvent("onmousemove", myFunction);
}
}