2016-02-26 44 views
0

我有一個Eventlistener,可以改變CSS的位置。現在我想設置第二個功能,它可以刪除以前的Eventlistener。這是HTML代碼:如何在Javascript中刪除eventListener?

<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> 

DA這是使用Javascript:

<script> 
function myFunction() { 

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


</script> 
+0

當你要刪除的事件偵聽器:

完整的答案以前被覆蓋? – Halcyon

+0

用戶執行myFunction()後。此外,框位置將改變「邊框」 – Giorgi

+0

重複http://stackoverflow.com/questions/4402287/javascript-remove-event-listener –

回答

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); 

注意兩個的addEventListenerremoveEventListener正在引用listener功能。您需要該參考以稍後移除事件偵聽器,即如何使用removeEventListener方法。 JavaScript: remove event listener