如何在Javascript中删除eventListener?

时间:2016-02-26 12:28:36

标签: javascript

我有一个Eventlistener,可以改变css位置。现在我想设置第二个函数,它可以删除以前的Eventlistener。这是HTML代码:

<style> 
div.container {
    width: 300px;
    border: 1px solid;
}

div.box {
    width: 150px;
    border: 3px solid coral;
    float: left;
    padding: 10px;
}
</style>
</head>
<body>

<div class="container">
<div class="box" id="box1">This is BOX1.</div>
<div class="box" id="box2">This is BOX2.</div>
<div style="clear:both;"></div>
</div>

<p>Two 150 pixels boxes inside a 300 pixels container. It should fit nicely, but because of the borders and padding, the two boxes take up more space than 150 pixels each. This "problem" can be solved by setting the boxSizing property to "border-box".</p>




<button onclick="myFunction()">Try it</button>

这是Javascript:

<script>
function myFunction() {

    document.getElementById("box1").style.boxSizing = "border-box";
    document.getElementById("box2").style.boxSizing = "border-box";
}


</script>

1 个答案:

答案 0 :(得分:1)

删除侦听器的最简洁方法是将其与 addEventListener 绑定,然后使用 removeEventListener 将其删除。 如:

var el = document.getElementById("myButton");

function listener(e) {
  // do things on event
}

// adding the event
el.addEventListener("click", listener, true);

// removing the event
el.removeEventListener("click", listener, true);

请注意, addEventListener removeEventListener 都是listener函数的参考。您需要该引用以便稍后删除事件侦听器,这就是removeEventListener方法的工作方式。

之前已完全回答: JavaScript: remove event listener