HTML - DOM removeEventListener() 方法



HTML DOM 的removeEventListener() 方法用於移除之前新增到元素上的事件監聽器。

JavaScript 中,事件監聽器是一個過程或函式,當指定事件發生時(例如“click”、“mouseover”或“mouseout”)執行。

語法

以下是 HTML DOM removeEventListener() 方法的語法:

element.removeEventListener(event, function, capture);

引數

此方法接受三個引數,如下所述:

引數 描述
event 您要移除的事件型別。
function 處理事件的函式。
capture 它是可選的,決定事件監聽器的移除。
它為捕獲階段設定“true”,為冒泡階段設定“false”(預設值)。

返回值

此方法不返回值。

示例 1:從按鈕中移除事件監聽器

以下是 HTML DOM removeEventListener() 方法的基本示例。它演示瞭如何在單擊按鈕時從元素中移除事件監聽器:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM removeEventListener()</title>
<style>
   button{
      padding: 8px;
   }
</style>
</head>
<body>
<p>Click Remove Listener to remove event handler.</h2>
<br><br>
<button class="myButton">Button 1</button> 
<button id="removeButton">Remove Listeners</button>
<div id="output"></div>
<script>
   const buttons = document.querySelectorAll('.myButton');
   const output = document.getElementById('output');
   const clickHandler = () => {
       output.textContent = 'Button clicked!';
   };
   buttons.forEach(button => button.addEventListener
   ('click', clickHandler));
   document.getElementById('removeButton').addEventListener('click', () =>{
       buttons.forEach(button =>button.removeEventListener
       ('click', clickHandler));
       output.textContent='Event listeners removed!';
   });
</script>
</body>
</html>    

示例 2:設定和移除 Div 元素的樣式

以下是 HTML DOM removeEventListener() 方法的另一個示例。此程式碼包含兩個按鈕。一個按鈕用於將事件監聽器新增到<div> 元素,另一個按鈕用於從該元素中移除事件監聽器:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM removeEventListener()</title>
<style>
   .highlighted {
       background-color: yellow;
       padding: 10px;
       border: 1px solid orange;
       margin-top: 10px;
   }
   button{
       padding: 8px;
 }
</style>
</head>
<body>
<h1>HTML - DOM Element</h1>
<h2>removeEventListener() Method</h2>
<p>This example set and remove the styles by using the event handler..</p>
<button id="hb">Highlight</button>
<button id="rb">Remove Style</button>
<div id="content">This is a div element.</div>
<script>
   const ele = document.getElementById('content');
   const hib = document.getElementById('hb');
   const reb = document.getElementById('rb');
   
   const highlightDiv = () => {
      ele.classList.add('highlighted');
   };
   
   const resetDiv = () => {
      ele.classList.remove('highlighted');
   }; 
   hib.addEventListener('click', highlightDiv);
   reb.addEventListener('click',function resetAndRemove(){
      resetDiv();
      hib.removeEventListener('click', highlightDiv);
      reb.removeEventListener('click', resetAndRemove);
   });
</script>
</body>
</html>    

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
removeEventListener()
html_dom_element_reference.htm
廣告