JavaScript中的事件响应

1、通过 addEventListener() 方法为某个元素添加事件监听:

     document.getElementById("myBtn").addEventListener("click", function(){.....});

 

2、removeEventListener() 方法移除某个元素的监听事件:

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
    background-color: coral;
    border: 1px solid;
    padding: 50px;
    color: white;
}
</style>
</head>
<body>

<div id="myDIV"> div 元素添加了 onmousemove 事件句柄,鼠标在桔红色的框内移动时会显示随机数。
  <p>点击按钮移除 DIV 的事件句柄。</p>
  <button onclick="removeHandler()" id="myBtn">点我</button>
</div>

<p id="demo"></p>

<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
    document.getElementById("demo").innerHTML = Math.random();
}

function removeHandler() {
    document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>

</body>
</html>

 

posted @ 2016-07-08 18:00  RoperLee  阅读(154)  评论(0)    收藏  举报