活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

掌握HTML DOM事件监听添加技巧提升网页交互体验从基础addEventListener到高级事件委托全面解析

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-15 12:40:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在现代网页开发中,交互性是提升用户体验的关键因素。用户与网页的每一次互动,如点击按钮、滚动页面、填写表单等,都是通过DOM事件来实现的。掌握DOM事件监听技术,能够让开发者创建出响应迅速、交互流畅的网页应用。本文将从基础的addEventListener方法开始,逐步深入到高级的事件委托技术,全面解析HTML DOM事件监听的添加技巧,帮助开发者提升网页交互体验。

DOM事件基础

什么是DOM事件

DOM(Document Object Model)事件是用户或浏览器自身执行的某种动作,例如点击、加载、鼠标移动等。这些事件可以被JavaScript监听并作出响应,从而实现交互功能。

事件类型

DOM事件可以分为以下几类:

1. 鼠标事件:click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout等
2. 键盘事件:keydown, keyup, keypress等
3. 表单事件:submit, change, focus, blur等
4. 文档/窗口事件:load, resize, scroll, unload等
5. 触摸事件:touchstart, touchmove, touchend等(移动设备)

事件流

事件流描述的是从页面中接收事件的顺序。主要有两种事件流模型:

1. 事件冒泡(Event Bubbling):事件开始时由最具体的元素(文档中嵌套层次最深的那个节点)接收,然后逐级向上传播到较为不具体的节点(文档)。
2. 事件捕获(Event Capturing):不太具体的节点应该更早接收到事件,而最具体的节点应该最后接收到事件。

addEventListener基础用法

基本语法

addEventListener是DOM元素提供的方法,用于添加事件监听器。其基本语法如下:
  1. element.addEventListener(event, function, useCapture);
复制代码

参数说明:

• event:字符串,表示要监听的事件类型(如”click”、”mouseover”等)
• function:事件触发时执行的函数,也称为事件处理函数
• useCapture:布尔值,可选参数,指定事件是在捕获阶段还是冒泡阶段处理,默认为false(冒泡阶段)

基本示例

下面是一个简单的点击事件监听示例:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>addEventListener基础示例</title>
  7.     <style>
  8.         button {
  9.             padding: 10px 15px;
  10.             font-size: 16px;
  11.             cursor: pointer;
  12.         }
  13.     </style>
  14. </head>
  15. <body>
  16.     <button id="myButton">点击我</button>
  17.     <p id="message"></p>
  18.     <script>
  19.         // 获取按钮元素
  20.         const button = document.getElementById('myButton');
  21.         const message = document.getElementById('message');
  22.         
  23.         // 添加点击事件监听器
  24.         button.addEventListener('click', function() {
  25.             message.textContent = '按钮被点击了!';
  26.         });
  27.     </script>
  28. </body>
  29. </html>
复制代码

在这个示例中,当用户点击按钮时,会触发一个匿名函数,该函数会在页面上显示一条消息。

事件处理函数的多种形式

使用命名函数

除了匿名函数,我们还可以使用命名函数作为事件处理函数:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>命名函数作为事件处理函数</title>
  7.     <style>
  8.         button {
  9.             padding: 10px 15px;
  10.             font-size: 16px;
  11.             cursor: pointer;
  12.         }
  13.     </style>
  14. </head>
  15. <body>
  16.     <button id="myButton">点击我</button>
  17.     <p id="message"></p>
  18.     <script>
  19.         // 获取按钮元素
  20.         const button = document.getElementById('myButton');
  21.         const message = document.getElementById('message');
  22.         
  23.         // 定义命名函数
  24.         function handleClick() {
  25.             message.textContent = '按钮被点击了!';
  26.         }
  27.         
  28.         // 添加点击事件监听器
  29.         button.addEventListener('click', handleClick);
  30.     </script>
  31. </body>
  32. </html>
复制代码

使用命名函数的好处是可以在需要时移除事件监听器,也可以在其他地方重用这个函数。

使用箭头函数

ES6引入的箭头函数也可以作为事件处理函数:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>箭头函数作为事件处理函数</title>
  7.     <style>
  8.         button {
  9.             padding: 10px 15px;
  10.             font-size: 16px;
  11.             cursor: pointer;
  12.         }
  13.     </style>
  14. </head>
  15. <body>
  16.     <button id="myButton">点击我</button>
  17.     <p id="message"></p>
  18.     <script>
  19.         // 获取按钮元素
  20.         const button = document.getElementById('myButton');
  21.         const message = document.getElementById('message');
  22.         
  23.         // 添加点击事件监听器,使用箭头函数
  24.         button.addEventListener('click', () => {
  25.             message.textContent = '按钮被点击了!';
  26.         });
  27.     </script>
  28. </body>
  29. </html>
复制代码

需要注意的是,箭头函数没有自己的this绑定,它会捕获其所在上下文的this值。这在某些情况下可能会导致不同的行为。

带参数的事件处理函数

有时我们需要向事件处理函数传递额外的参数,可以通过以下方式实现:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>带参数的事件处理函数</title>
  7.     <style>
  8.         button {
  9.             padding: 10px 15px;
  10.             margin: 5px;
  11.             font-size: 16px;
  12.             cursor: pointer;
  13.         }
  14.     </style>
  15. </head>
  16. <body>
  17.     <button id="btn1">按钮1</button>
  18.     <button id="btn2">按钮2</button>
  19.     <p id="message"></p>
  20.     <script>
  21.         // 获取按钮元素
  22.         const btn1 = document.getElementById('btn1');
  23.         const btn2 = document.getElementById('btn2');
  24.         const message = document.getElementById('message');
  25.         
  26.         // 定义带参数的函数
  27.         function showMessage(buttonName, event) {
  28.             message.textContent = `${buttonName} 被点击了!`;
  29.             console.log('事件对象:', event);
  30.         }
  31.         
  32.         // 添加点击事件监听器,使用匿名函数包装
  33.         btn1.addEventListener('click', function(event) {
  34.             showMessage('按钮1', event);
  35.         });
  36.         
  37.         // 使用箭头函数包装
  38.         btn2.addEventListener('click', (event) => {
  39.             showMessage('按钮2', event);
  40.         });
  41.     </script>
  42. </body>
  43. </html>
复制代码

事件对象详解

事件对象的属性和方法

当事件被触发时,浏览器会创建一个事件对象,包含与事件相关的信息。这个对象会作为参数传递给事件处理函数。

常用的事件对象属性和方法:

• type:事件类型(如”click”、”mouseover”等)
• target:触发事件的元素
• currentTarget:当前处理事件的元素(通常是添加事件监听器的元素)
• bubbles:布尔值,表示事件是否冒泡
• cancelable:布尔值,表示是否可以取消事件的默认行为
• defaultPrevented:布尔值,表示是否已经调用了preventDefault()
• eventPhase:整数,表示事件处理的阶段(1=捕获,2=目标,3=冒泡)
• timeStamp:事件发生的时间戳
• preventDefault():取消事件的默认行为
• stopPropagation():停止事件的传播

事件对象示例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件对象示例</title>
  7.     <style>
  8.         #container {
  9.             width: 300px;
  10.             height: 200px;
  11.             background-color: #f0f0f0;
  12.             padding: 20px;
  13.             border: 1px solid #ccc;
  14.         }
  15.         
  16.         #inner {
  17.             width: 150px;
  18.             height: 100px;
  19.             background-color: #e0e0e0;
  20.             padding: 10px;
  21.             border: 1px solid #999;
  22.         }
  23.     </style>
  24. </head>
  25. <body>
  26.     <div id="container">
  27.         外层容器
  28.         <div id="inner">内层元素</div>
  29.     </div>
  30.     <div id="output"></div>
  31.     <script>
  32.         const container = document.getElementById('container');
  33.         const inner = document.getElementById('inner');
  34.         const output = document.getElementById('output');
  35.         
  36.         function logEventInfo(event, elementName) {
  37.             output.innerHTML += `
  38.                 <p><strong>${elementName}</strong> - 事件类型: ${event.type},
  39.                 目标元素: ${event.target.id},
  40.                 当前元素: ${event.currentTarget.id},
  41.                 事件阶段: ${event.eventPhase}</p>
  42.             `;
  43.         }
  44.         
  45.         // 添加事件监听器
  46.         container.addEventListener('click', function(event) {
  47.             logEventInfo(event, '外层容器');
  48.         });
  49.         
  50.         inner.addEventListener('click', function(event) {
  51.             logEventInfo(event, '内层元素');
  52.         });
  53.     </script>
  54. </body>
  55. </html>
复制代码

在这个示例中,点击内层元素时,事件会冒泡到外层容器,两个事件处理函数都会被调用。通过事件对象,我们可以看到事件的目标元素、当前元素以及事件处理的阶段。

事件移除

removeEventListener方法

要移除已添加的事件监听器,可以使用removeEventListener方法。其语法与addEventListener类似:
  1. element.removeEventListener(event, function, useCapture);
复制代码

需要注意的是,要成功移除事件监听器,传递给removeEventListener的参数必须与addEventListener时使用的参数完全相同。这意味着如果使用匿名函数添加事件监听器,将无法移除它。

事件移除示例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件移除示例</title>
  7.     <style>
  8.         button {
  9.             padding: 10px 15px;
  10.             margin: 5px;
  11.             font-size: 16px;
  12.             cursor: pointer;
  13.         }
  14.         
  15.         #output {
  16.             margin-top: 20px;
  17.             padding: 10px;
  18.             background-color: #f0f0f0;
  19.             border: 1px solid #ccc;
  20.         }
  21.     </style>
  22. </head>
  23. <body>
  24.     <button id="clickBtn">点击我</button>
  25.     <button id="removeBtn">移除事件监听器</button>
  26.     <div id="output"></div>
  27.     <script>
  28.         const clickBtn = document.getElementById('clickBtn');
  29.         const removeBtn = document.getElementById('removeBtn');
  30.         const output = document.getElementById('output');
  31.         let clickCount = 0;
  32.         
  33.         // 定义命名函数作为事件处理函数
  34.         function handleClick() {
  35.             clickCount++;
  36.             output.textContent = `按钮被点击了 ${clickCount} 次`;
  37.         }
  38.         
  39.         // 添加事件监听器
  40.         clickBtn.addEventListener('click', handleClick);
  41.         
  42.         // 添加移除事件监听器的按钮
  43.         removeBtn.addEventListener('click', function() {
  44.             clickBtn.removeEventListener('click', handleClick);
  45.             output.textContent = `事件监听器已移除。按钮被点击了 ${clickCount} 次`;
  46.         });
  47.     </script>
  48. </body>
  49. </html>
复制代码

在这个示例中,我们使用命名函数handleClick作为事件处理函数,这样就可以在需要时通过removeEventListener移除它。

事件冒泡与捕获

事件流阶段

DOM2级事件规定事件流包括三个阶段:

1. 事件捕获阶段:事件从document对象向下传播到目标元素
2. 目标阶段:事件到达目标元素
3. 事件冒泡阶段:事件从目标元素向上传播回document对象

控制事件流

通过addEventListener的第三个参数useCapture,我们可以控制事件是在捕获阶段还是冒泡阶段处理:
  1. // 在捕获阶段处理事件
  2. element.addEventListener(event, handler, true);
  3. // 在冒泡阶段处理事件(默认)
  4. element.addEventListener(event, handler, false);
  5. element.addEventListener(event, handler); // 默认为false
复制代码

事件冒泡与捕获示例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件冒泡与捕获示例</title>
  7.     <style>
  8.         #outer {
  9.             width: 300px;
  10.             height: 200px;
  11.             background-color: #f0f0f0;
  12.             padding: 20px;
  13.             border: 1px solid #ccc;
  14.             position: relative;
  15.         }
  16.         
  17.         #middle {
  18.             width: 200px;
  19.             height: 120px;
  20.             background-color: #d0d0d0;
  21.             padding: 15px;
  22.             border: 1px solid #999;
  23.             position: absolute;
  24.             top: 30px;
  25.             left: 30px;
  26.         }
  27.         
  28.         #inner {
  29.             width: 100px;
  30.             height: 60px;
  31.             background-color: #b0b0b0;
  32.             padding: 10px;
  33.             border: 1px solid #777;
  34.             position: absolute;
  35.             top: 20px;
  36.             left: 20px;
  37.             text-align: center;
  38.             line-height: 40px;
  39.             cursor: pointer;
  40.         }
  41.         
  42.         #output {
  43.             margin-top: 220px;
  44.             padding: 10px;
  45.             background-color: #f9f9f9;
  46.             border: 1px solid #ddd;
  47.             height: 200px;
  48.             overflow-y: auto;
  49.         }
  50.         
  51.         .log-entry {
  52.             margin: 5px 0;
  53.             padding: 5px;
  54.             border-bottom: 1px solid #eee;
  55.         }
  56.         
  57.         .capture {
  58.             color: #0066cc;
  59.         }
  60.         
  61.         .bubble {
  62.             color: #cc6600;
  63.         }
  64.         
  65.         .target {
  66.             color: #009900;
  67.             font-weight: bold;
  68.         }
  69.     </style>
  70. </head>
  71. <body>
  72.     <div id="outer">外层
  73.         <div id="middle">中层
  74.             <div id="inner">内层</div>
  75.         </div>
  76.     </div>
  77.     <div id="output"></div>
  78.     <script>
  79.         const outer = document.getElementById('outer');
  80.         const middle = document.getElementById('middle');
  81.         const inner = document.getElementById('inner');
  82.         const output = document.getElementById('output');
  83.         
  84.         function logEvent(phase, element, event) {
  85.             const logEntry = document.createElement('div');
  86.             logEntry.className = `log-entry ${phase}`;
  87.             logEntry.textContent = `${phase}阶段: ${element} - 事件目标: ${event.target.id}`;
  88.             output.appendChild(logEntry);
  89.         }
  90.         
  91.         // 添加捕获阶段事件监听器
  92.         outer.addEventListener('click', function(event) {
  93.             logEvent('捕获', '外层', event);
  94.         }, true);
  95.         
  96.         middle.addEventListener('click', function(event) {
  97.             logEvent('捕获', '中层', event);
  98.         }, true);
  99.         
  100.         inner.addEventListener('click', function(event) {
  101.             logEvent('捕获', '内层', event);
  102.         }, true);
  103.         
  104.         // 添加冒泡阶段事件监听器
  105.         outer.addEventListener('click', function(event) {
  106.             logEvent('冒泡', '外层', event);
  107.         }, false);
  108.         
  109.         middle.addEventListener('click', function(event) {
  110.             logEvent('冒泡', '中层', event);
  111.         }, false);
  112.         
  113.         inner.addEventListener('click', function(event) {
  114.             logEvent('目标', '内层', event);
  115.         }, false);
  116.     </script>
  117. </body>
  118. </html>
复制代码

在这个示例中,我们在三个嵌套的元素上都添加了捕获阶段和冒泡阶段的事件监听器。当点击最内层的元素时,可以看到事件流的完整过程:先从外到内进行捕获,然后到达目标,最后从内到外进行冒泡。

阻止事件传播

有时我们需要阻止事件的传播,可以使用以下方法:

1. event.stopPropagation():阻止事件在DOM中传播,但不阻止默认行为
2. event.stopImmediatePropagation():阻止事件传播,并且阻止同一元素上的其他事件处理函数被调用
3. event.preventDefault():阻止事件的默认行为,但不阻止事件传播
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>阻止事件传播示例</title>
  7.     <style>
  8.         #outer {
  9.             width: 300px;
  10.             height: 200px;
  11.             background-color: #f0f0f0;
  12.             padding: 20px;
  13.             border: 1px solid #ccc;
  14.         }
  15.         
  16.         #inner {
  17.             width: 150px;
  18.             height: 100px;
  19.             background-color: #e0e0e0;
  20.             padding: 10px;
  21.             border: 1px solid #999;
  22.             margin-top: 20px;
  23.             text-align: center;
  24.             line-height: 80px;
  25.             cursor: pointer;
  26.         }
  27.         
  28.         #output {
  29.             margin-top: 20px;
  30.             padding: 10px;
  31.             background-color: #f9f9f9;
  32.             border: 1px solid #ddd;
  33.         }
  34.         
  35.         button {
  36.             margin: 5px;
  37.             padding: 8px 12px;
  38.         }
  39.     </style>
  40. </head>
  41. <body>
  42.     <div id="outer">外层元素
  43.         <div id="inner">内层元素</div>
  44.     </div>
  45.     <div>
  46.         <button id="stopPropagationBtn">使用stopPropagation</button>
  47.         <button id="stopImmediateBtn">使用stopImmediatePropagation</button>
  48.         <button id="resetBtn">重置</button>
  49.     </div>
  50.     <div id="output"></div>
  51.     <script>
  52.         const outer = document.getElementById('outer');
  53.         const inner = document.getElementById('inner');
  54.         const output = document.getElementById('output');
  55.         const stopPropagationBtn = document.getElementById('stopPropagationBtn');
  56.         const stopImmediateBtn = document.getElementById('stopImmediatePropagationBtn');
  57.         const resetBtn = document.getElementById('resetBtn');
  58.         
  59.         let stopPropagation = false;
  60.         let stopImmediatePropagation = false;
  61.         
  62.         function log(message) {
  63.             const p = document.createElement('p');
  64.             p.textContent = message;
  65.             output.appendChild(p);
  66.         }
  67.         
  68.         // 外层元素事件监听器
  69.         outer.addEventListener('click', function(event) {
  70.             log('外层元素点击事件触发');
  71.         });
  72.         
  73.         // 内层元素第一个事件监听器
  74.         inner.addEventListener('click', function(event) {
  75.             log('内层元素第一个点击事件触发');
  76.             
  77.             if (stopPropagation) {
  78.                 event.stopPropagation();
  79.                 log('事件传播已停止(stopPropagation)');
  80.             }
  81.             
  82.             if (stopImmediatePropagation) {
  83.                 event.stopImmediatePropagation();
  84.                 log('事件传播已立即停止(stopImmediatePropagation)');
  85.             }
  86.         });
  87.         
  88.         // 内层元素第二个事件监听器
  89.         inner.addEventListener('click', function(event) {
  90.             log('内层元素第二个点击事件触发');
  91.         });
  92.         
  93.         // 按钮事件监听器
  94.         stopPropagationBtn.addEventListener('click', function() {
  95.             stopPropagation = true;
  96.             stopImmediatePropagation = false;
  97.             output.innerHTML = '';
  98.             log('已设置使用stopPropagation');
  99.         });
  100.         
  101.         stopImmediateBtn.addEventListener('click', function() {
  102.             stopPropagation = false;
  103.             stopImmediatePropagation = true;
  104.             output.innerHTML = '';
  105.             log('已设置使用stopImmediatePropagation');
  106.         });
  107.         
  108.         resetBtn.addEventListener('click', function() {
  109.             stopPropagation = false;
  110.             stopImmediatePropagation = false;
  111.             output.innerHTML = '';
  112.             log('已重置');
  113.         });
  114.     </script>
  115. </body>
  116. </html>
复制代码

在这个示例中,我们可以通过按钮来测试stopPropagation和stopImmediatePropagation的效果。当使用stopPropagation时,事件不会传播到父元素,但同一元素上的其他事件处理函数仍会被调用。而当使用stopImmediatePropagation时,不仅事件不会传播,同一元素上的其他事件处理函数也不会被调用。

事件委托

什么是事件委托

事件委托是一种利用事件冒泡机制的技术,通过在父元素上设置事件监听器来管理其所有子元素的事件。这样做的好处是:

1. 减少内存使用:只需要一个事件监听器,而不是为每个子元素都添加一个
2. 动态元素支持:可以处理动态添加到DOM中的元素的事件
3. 简化代码:不需要为每个元素单独添加事件监听器

事件委托的基本实现
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件委托基本实现</title>
  7.     <style>
  8.         #buttonContainer {
  9.             margin: 20px 0;
  10.         }
  11.         
  12.         button {
  13.             padding: 8px 12px;
  14.             margin: 5px;
  15.             cursor: pointer;
  16.         }
  17.         
  18.         #output {
  19.             padding: 10px;
  20.             background-color: #f9f9f9;
  21.             border: 1px solid #ddd;
  22.             min-height: 50px;
  23.         }
  24.         
  25.         #addButton {
  26.             background-color: #4CAF50;
  27.             color: white;
  28.             border: none;
  29.             padding: 10px 15px;
  30.             margin-top: 10px;
  31.         }
  32.     </style>
  33. </head>
  34. <body>
  35.     <h2>事件委托示例</h2>
  36.     <div id="buttonContainer">
  37.         <button class="action-btn" data-action="save">保存</button>
  38.         <button class="action-btn" data-action="delete">删除</button>
  39.         <button class="action-btn" data-action="edit">编辑</button>
  40.     </div>
  41.     <button id="addButton">添加新按钮</button>
  42.     <div id="output"></div>
  43.     <script>
  44.         const buttonContainer = document.getElementById('buttonContainer');
  45.         const addButton = document.getElementById('addButton');
  46.         const output = document.getElementById('output');
  47.         let buttonCount = 3;
  48.         
  49.         // 使用事件委托,在父元素上添加事件监听器
  50.         buttonContainer.addEventListener('click', function(event) {
  51.             // 检查点击的元素是否是我们感兴趣的按钮
  52.             if (event.target.classList.contains('action-btn')) {
  53.                 const action = event.target.getAttribute('data-action');
  54.                 output.textContent = `执行了 ${action} 操作`;
  55.             }
  56.         });
  57.         
  58.         // 添加新按钮的功能
  59.         addButton.addEventListener('click', function() {
  60.             buttonCount++;
  61.             const newButton = document.createElement('button');
  62.             newButton.className = 'action-btn';
  63.             newButton.setAttribute('data-action', `新操作${buttonCount}`);
  64.             newButton.textContent = `新操作${buttonCount}`;
  65.             buttonContainer.appendChild(newButton);
  66.             
  67.             output.textContent = `添加了新按钮:新操作${buttonCount}`;
  68.         });
  69.     </script>
  70. </body>
  71. </html>
复制代码

在这个示例中,我们在父元素buttonContainer上添加了一个事件监听器,通过检查event.target的类名和属性来确定点击的是哪个按钮。这样,即使动态添加新的按钮,也不需要为它们单独添加事件监听器。

事件委托的高级应用
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件委托高级应用</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 800px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         
  15.         #todoList {
  16.             list-style: none;
  17.             padding: 0;
  18.         }
  19.         
  20.         .todo-item {
  21.             display: flex;
  22.             align-items: center;
  23.             padding: 10px;
  24.             border-bottom: 1px solid #eee;
  25.         }
  26.         
  27.         .todo-item.completed {
  28.             text-decoration: line-through;
  29.             color: #999;
  30.         }
  31.         
  32.         .todo-text {
  33.             flex-grow: 1;
  34.             margin: 0 10px;
  35.         }
  36.         
  37.         .todo-checkbox {
  38.             margin-right: 10px;
  39.         }
  40.         
  41.         .delete-btn {
  42.             background-color: #ff4444;
  43.             color: white;
  44.             border: none;
  45.             padding: 5px 10px;
  46.             cursor: pointer;
  47.             border-radius: 3px;
  48.         }
  49.         
  50.         .add-todo {
  51.             display: flex;
  52.             margin-top: 20px;
  53.         }
  54.         
  55.         .add-todo input {
  56.             flex-grow: 1;
  57.             padding: 8px;
  58.             border: 1px solid #ddd;
  59.             border-radius: 3px;
  60.         }
  61.         
  62.         .add-todo button {
  63.             background-color: #4CAF50;
  64.             color: white;
  65.             border: none;
  66.             padding: 8px 15px;
  67.             margin-left: 10px;
  68.             cursor: pointer;
  69.             border-radius: 3px;
  70.         }
  71.         
  72.         .filter-buttons {
  73.             margin: 20px 0;
  74.         }
  75.         
  76.         .filter-buttons button {
  77.             background-color: #f0f0f0;
  78.             border: 1px solid #ddd;
  79.             padding: 5px 10px;
  80.             margin-right: 5px;
  81.             cursor: pointer;
  82.         }
  83.         
  84.         .filter-buttons button.active {
  85.             background-color: #4CAF50;
  86.             color: white;
  87.         }
  88.     </style>
  89. </head>
  90. <body>
  91.     <h1>待办事项列表</h1>
  92.    
  93.     <div class="filter-buttons">
  94.         <button class="filter-btn active" data-filter="all">全部</button>
  95.         <button class="filter-btn" data-filter="active">未完成</button>
  96.         <button class="filter-btn" data-filter="completed">已完成</button>
  97.     </div>
  98.    
  99.     <ul id="todoList">
  100.         <li class="todo-item" data-id="1">
  101.             <input type="checkbox" class="todo-checkbox">
  102.             <span class="todo-text">学习JavaScript</span>
  103.             <button class="delete-btn">删除</button>
  104.         </li>
  105.         <li class="todo-item" data-id="2">
  106.             <input type="checkbox" class="todo-checkbox">
  107.             <span class="todo-text">学习HTML</span>
  108.             <button class="delete-btn">删除</button>
  109.         </li>
  110.         <li class="todo-item completed" data-id="3">
  111.             <input type="checkbox" class="todo-checkbox" checked>
  112.             <span class="todo-text">学习CSS</span>
  113.             <button class="delete-btn">删除</button>
  114.         </li>
  115.     </ul>
  116.    
  117.     <div class="add-todo">
  118.         <input type="text" id="newTodoInput" placeholder="添加新的待办事项">
  119.         <button id="addTodoBtn">添加</button>
  120.     </div>
  121.     <script>
  122.         const todoList = document.getElementById('todoList');
  123.         const newTodoInput = document.getElementById('newTodoInput');
  124.         const addTodoBtn = document.getElementById('addTodoBtn');
  125.         const filterButtons = document.querySelectorAll('.filter-btn');
  126.         let nextId = 4;
  127.         let currentFilter = 'all';
  128.         
  129.         // 使用事件委托处理待办事项列表的点击事件
  130.         todoList.addEventListener('click', function(event) {
  131.             const target = event.target;
  132.             const todoItem = target.closest('.todo-item');
  133.             
  134.             if (!todoItem) return;
  135.             
  136.             // 处理复选框点击
  137.             if (target.classList.contains('todo-checkbox')) {
  138.                 todoItem.classList.toggle('completed', target.checked);
  139.                 applyFilter();
  140.             }
  141.             
  142.             // 处理删除按钮点击
  143.             if (target.classList.contains('delete-btn')) {
  144.                 todoItem.remove();
  145.             }
  146.         });
  147.         
  148.         // 使用事件委托处理过滤按钮的点击事件
  149.         document.querySelector('.filter-buttons').addEventListener('click', function(event) {
  150.             if (event.target.classList.contains('filter-btn')) {
  151.                 // 更新活动按钮
  152.                 filterButtons.forEach(btn => btn.classList.remove('active'));
  153.                 event.target.classList.add('active');
  154.                
  155.                 // 更新当前过滤器并应用
  156.                 currentFilter = event.target.getAttribute('data-filter');
  157.                 applyFilter();
  158.             }
  159.         });
  160.         
  161.         // 添加新的待办事项
  162.         addTodoBtn.addEventListener('click', addNewTodo);
  163.         newTodoInput.addEventListener('keypress', function(event) {
  164.             if (event.key === 'Enter') {
  165.                 addNewTodo();
  166.             }
  167.         });
  168.         
  169.         function addNewTodo() {
  170.             const todoText = newTodoInput.value.trim();
  171.             if (!todoText) return;
  172.             
  173.             const newTodo = document.createElement('li');
  174.             newTodo.className = 'todo-item';
  175.             newTodo.setAttribute('data-id', nextId++);
  176.             newTodo.innerHTML = `
  177.                 <input type="checkbox" class="todo-checkbox">
  178.                 <span class="todo-text">${todoText}</span>
  179.                 <button class="delete-btn">删除</button>
  180.             `;
  181.             
  182.             todoList.appendChild(newTodo);
  183.             newTodoInput.value = '';
  184.             applyFilter();
  185.         }
  186.         
  187.         // 应用当前过滤器
  188.         function applyFilter() {
  189.             const todoItems = document.querySelectorAll('.todo-item');
  190.             
  191.             todoItems.forEach(item => {
  192.                 switch (currentFilter) {
  193.                     case 'all':
  194.                         item.style.display = 'flex';
  195.                         break;
  196.                     case 'active':
  197.                         item.style.display = item.classList.contains('completed') ? 'none' : 'flex';
  198.                         break;
  199.                     case 'completed':
  200.                         item.style.display = item.classList.contains('completed') ? 'flex' : 'none';
  201.                         break;
  202.                 }
  203.             });
  204.         }
  205.     </script>
  206. </body>
  207. </html>
复制代码

这个待办事项列表应用展示了事件委托的高级应用。我们在父元素todoList上添加了一个事件监听器,处理所有子元素的点击事件,包括复选框和删除按钮。同样,我们在过滤按钮的父元素上添加了事件监听器,处理所有过滤按钮的点击事件。这样,即使动态添加新的待办事项,也不需要为它们单独添加事件监听器。

最佳实践与性能优化

事件监听器的最佳实践

1. 使用事件委托:对于有多个子元素需要相同事件处理的情况,使用事件委托可以减少内存使用并简化代码。
2. 避免在循环中添加事件监听器:在循环中为多个元素添加事件监听器会导致性能问题,应该使用事件委托。
3. 及时移除不需要的事件监听器:当元素被移除或不再需要事件监听时,应该使用removeEventListener移除它们,避免内存泄漏。
4. 使用被动事件监听器提高滚动性能:对于wheel和touchstart等事件,可以使用passive: true选项来提高滚动性能。

使用事件委托:对于有多个子元素需要相同事件处理的情况,使用事件委托可以减少内存使用并简化代码。

避免在循环中添加事件监听器:在循环中为多个元素添加事件监听器会导致性能问题,应该使用事件委托。

及时移除不需要的事件监听器:当元素被移除或不再需要事件监听时,应该使用removeEventListener移除它们,避免内存泄漏。

使用被动事件监听器提高滚动性能:对于wheel和touchstart等事件,可以使用passive: true选项来提高滚动性能。
  1. // 使用被动事件监听器
  2. element.addEventListener('wheel', handler, { passive: true });
  3. element.addEventListener('touchstart', handler, { passive: true });
复制代码

1. 使用事件节流和防抖:对于频繁触发的事件(如resize、scroll),使用节流(throttle)和防抖(debounce)技术来限制事件处理函数的调用频率。

事件节流和防抖示例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>事件节流和防抖示例</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 800px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         
  15.         .box {
  16.             width: 100%;
  17.             height: 200px;
  18.             border: 1px solid #ccc;
  19.             margin: 20px 0;
  20.             overflow-y: auto;
  21.             padding: 10px;
  22.         }
  23.         
  24.         .content {
  25.             height: 1000px;
  26.             background: linear-gradient(to bottom, #f0f0f0, #ddd);
  27.         }
  28.         
  29.         .counter {
  30.             margin: 10px 0;
  31.             padding: 10px;
  32.             background-color: #f9f9f9;
  33.             border: 1px solid #ddd;
  34.         }
  35.         
  36.         button {
  37.             padding: 8px 12px;
  38.             margin: 5px;
  39.             cursor: pointer;
  40.         }
  41.         
  42.         .active {
  43.             background-color: #4CAF50;
  44.             color: white;
  45.         }
  46.     </style>
  47. </head>
  48. <body>
  49.     <h1>事件节流和防抖示例</h1>
  50.    
  51.     <div>
  52.         <button id="normalBtn" class="active">普通滚动事件</button>
  53.         <button id="throttleBtn">节流滚动事件</button>
  54.         <button id="debounceBtn">防抖滚动事件</button>
  55.     </div>
  56.    
  57.     <div class="counter">
  58.         普通事件触发次数: <span id="normalCount">0</span>
  59.     </div>
  60.    
  61.     <div class="counter">
  62.         节流事件触发次数: <span id="throttleCount">0</span>
  63.     </div>
  64.    
  65.     <div class="counter">
  66.         防抖事件触发次数: <span id="debounceCount">0</span>
  67.     </div>
  68.    
  69.     <div class="box" id="scrollBox">
  70.         <div class="content">滚动此区域测试事件节流和防抖效果</div>
  71.     </div>
  72.     <script>
  73.         const scrollBox = document.getElementById('scrollBox');
  74.         const normalCount = document.getElementById('normalCount');
  75.         const throttleCount = document.getElementById('throttleCount');
  76.         const debounceCount = document.getElementById('debounceCount');
  77.         const normalBtn = document.getElementById('normalBtn');
  78.         const throttleBtn = document.getElementById('throttleBtn');
  79.         const debounceBtn = document.getElementById('debounceBtn');
  80.         
  81.         let normalCounter = 0;
  82.         let throttleCounter = 0;
  83.         let debounceCounter = 0;
  84.         
  85.         // 节流函数
  86.         function throttle(func, delay) {
  87.             let lastCall = 0;
  88.             return function(...args) {
  89.                 const now = new Date().getTime();
  90.                 if (now - lastCall < delay) {
  91.                     return;
  92.                 }
  93.                 lastCall = now;
  94.                 return func.apply(this, args);
  95.             };
  96.         }
  97.         
  98.         // 防抖函数
  99.         function debounce(func, delay) {
  100.             let timeoutId;
  101.             return function(...args) {
  102.                 clearTimeout(timeoutId);
  103.                 timeoutId = setTimeout(() => {
  104.                     func.apply(this, args);
  105.                 }, delay);
  106.             };
  107.         }
  108.         
  109.         // 普通滚动事件处理函数
  110.         function handleNormalScroll() {
  111.             normalCounter++;
  112.             normalCount.textContent = normalCounter;
  113.         }
  114.         
  115.         // 节流滚动事件处理函数
  116.         function handleThrottleScroll() {
  117.             throttleCounter++;
  118.             throttleCount.textContent = throttleCounter;
  119.         }
  120.         
  121.         // 防抖滚动事件处理函数
  122.         function handleDebounceScroll() {
  123.             debounceCounter++;
  124.             debounceCount.textContent = debounceCounter;
  125.         }
  126.         
  127.         // 创建节流和防抖版本的事件处理函数
  128.         const throttledScrollHandler = throttle(handleThrottleScroll, 200);
  129.         const debouncedScrollHandler = debounce(handleDebounceScroll, 200);
  130.         
  131.         // 初始状态:只使用普通滚动事件
  132.         scrollBox.addEventListener('scroll', handleNormalScroll);
  133.         
  134.         // 按钮事件处理
  135.         normalBtn.addEventListener('click', function() {
  136.             // 移除所有事件监听器
  137.             scrollBox.removeEventListener('scroll', handleNormalScroll);
  138.             scrollBox.removeEventListener('scroll', throttledScrollHandler);
  139.             scrollBox.removeEventListener('scroll', debouncedScrollHandler);
  140.             
  141.             // 添加普通滚动事件监听器
  142.             scrollBox.addEventListener('scroll', handleNormalScroll);
  143.             
  144.             // 更新按钮状态
  145.             normalBtn.classList.add('active');
  146.             throttleBtn.classList.remove('active');
  147.             debounceBtn.classList.remove('active');
  148.             
  149.             // 重置计数器
  150.             normalCounter = 0;
  151.             throttleCounter = 0;
  152.             debounceCounter = 0;
  153.             normalCount.textContent = '0';
  154.             throttleCount.textContent = '0';
  155.             debounceCount.textContent = '0';
  156.         });
  157.         
  158.         throttleBtn.addEventListener('click', function() {
  159.             // 移除所有事件监听器
  160.             scrollBox.removeEventListener('scroll', handleNormalScroll);
  161.             scrollBox.removeEventListener('scroll', throttledScrollHandler);
  162.             scrollBox.removeEventListener('scroll', debouncedScrollHandler);
  163.             
  164.             // 添加节流滚动事件监听器
  165.             scrollBox.addEventListener('scroll', handleNormalScroll);
  166.             scrollBox.addEventListener('scroll', throttledScrollHandler);
  167.             
  168.             // 更新按钮状态
  169.             normalBtn.classList.remove('active');
  170.             throttleBtn.classList.add('active');
  171.             debounceBtn.classList.remove('active');
  172.             
  173.             // 重置计数器
  174.             normalCounter = 0;
  175.             throttleCounter = 0;
  176.             debounceCounter = 0;
  177.             normalCount.textContent = '0';
  178.             throttleCount.textContent = '0';
  179.             debounceCount.textContent = '0';
  180.         });
  181.         
  182.         debounceBtn.addEventListener('click', function() {
  183.             // 移除所有事件监听器
  184.             scrollBox.removeEventListener('scroll', handleNormalScroll);
  185.             scrollBox.removeEventListener('scroll', throttledScrollHandler);
  186.             scrollBox.removeEventListener('scroll', debouncedScrollHandler);
  187.             
  188.             // 添加防抖滚动事件监听器
  189.             scrollBox.addEventListener('scroll', handleNormalScroll);
  190.             scrollBox.addEventListener('scroll', debouncedScrollHandler);
  191.             
  192.             // 更新按钮状态
  193.             normalBtn.classList.remove('active');
  194.             throttleBtn.classList.add('active');
  195.             debounceBtn.classList.remove('active');
  196.             
  197.             // 重置计数器
  198.             normalCounter = 0;
  199.             throttleCounter = 0;
  200.             debounceCounter = 0;
  201.             normalCount.textContent = '0';
  202.             throttleCount.textContent = '0';
  203.             debounceCount.textContent = '0';
  204.         });
  205.     </script>
  206. </body>
  207. </html>
复制代码

在这个示例中,我们实现了事件节流和防抖的功能,并通过一个可滚动的区域来测试它们的效果。节流函数确保事件处理函数在一定时间内只执行一次,而防抖函数确保事件处理函数只在事件停止触发一段时间后执行。

实际应用案例

动态表格操作
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>动态表格操作</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 1000px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         
  15.         table {
  16.             width: 100%;
  17.             border-collapse: collapse;
  18.             margin: 20px 0;
  19.         }
  20.         
  21.         th, td {
  22.             border: 1px solid #ddd;
  23.             padding: 8px;
  24.             text-align: left;
  25.         }
  26.         
  27.         th {
  28.             background-color: #f2f2f2;
  29.         }
  30.         
  31.         tr:hover {
  32.             background-color: #f5f5f5;
  33.         }
  34.         
  35.         .action-btn {
  36.             padding: 4px 8px;
  37.             margin: 0 2px;
  38.             cursor: pointer;
  39.             border: none;
  40.             border-radius: 3px;
  41.         }
  42.         
  43.         .edit-btn {
  44.             background-color: #4CAF50;
  45.             color: white;
  46.         }
  47.         
  48.         .delete-btn {
  49.             background-color: #f44336;
  50.             color: white;
  51.         }
  52.         
  53.         .save-btn {
  54.             background-color: #2196F3;
  55.             color: white;
  56.         }
  57.         
  58.         .cancel-btn {
  59.             background-color: #9e9e9e;
  60.             color: white;
  61.         }
  62.         
  63.         .add-form {
  64.             display: flex;
  65.             margin: 20px 0;
  66.             gap: 10px;
  67.         }
  68.         
  69.         .add-form input {
  70.             padding: 8px;
  71.             border: 1px solid #ddd;
  72.             border-radius: 3px;
  73.         }
  74.         
  75.         .add-form button {
  76.             padding: 8px 15px;
  77.             background-color: #4CAF50;
  78.             color: white;
  79.             border: none;
  80.             border-radius: 3px;
  81.             cursor: pointer;
  82.         }
  83.         
  84.         .notification {
  85.             padding: 10px;
  86.             margin: 10px 0;
  87.             border-radius: 3px;
  88.             display: none;
  89.         }
  90.         
  91.         .success {
  92.             background-color: #dff0d8;
  93.             color: #3c763d;
  94.             border: 1px solid #d6e9c6;
  95.         }
  96.         
  97.         .error {
  98.             background-color: #f2dede;
  99.             color: #a94442;
  100.             border: 1px solid #ebccd1;
  101.         }
  102.     </style>
  103. </head>
  104. <body>
  105.     <h1>员工信息管理</h1>
  106.    
  107.     <div class="notification" id="notification"></div>
  108.    
  109.     <div class="add-form">
  110.         <input type="text" id="nameInput" placeholder="姓名">
  111.         <input type="text" id="positionInput" placeholder="职位">
  112.         <input type="email" id="emailInput" placeholder="邮箱">
  113.         <button id="addBtn">添加员工</button>
  114.     </div>
  115.    
  116.     <table id="employeeTable">
  117.         <thead>
  118.             <tr>
  119.                 <th>ID</th>
  120.                 <th>姓名</th>
  121.                 <th>职位</th>
  122.                 <th>邮箱</th>
  123.                 <th>操作</th>
  124.             </tr>
  125.         </thead>
  126.         <tbody>
  127.             <tr data-id="1">
  128.                 <td>1</td>
  129.                 <td>张三</td>
  130.                 <td>前端开发</td>
  131.                 <td>zhangsan@example.com</td>
  132.                 <td>
  133.                     <button class="action-btn edit-btn">编辑</button>
  134.                     <button class="action-btn delete-btn">删除</button>
  135.                 </td>
  136.             </tr>
  137.             <tr data-id="2">
  138.                 <td>2</td>
  139.                 <td>李四</td>
  140.                 <td>后端开发</td>
  141.                 <td>lisi@example.com</td>
  142.                 <td>
  143.                     <button class="action-btn edit-btn">编辑</button>
  144.                     <button class="action-btn delete-btn">删除</button>
  145.                 </td>
  146.             </tr>
  147.             <tr data-id="3">
  148.                 <td>3</td>
  149.                 <td>王五</td>
  150.                 <td>产品经理</td>
  151.                 <td>wangwu@example.com</td>
  152.                 <td>
  153.                     <button class="action-btn edit-btn">编辑</button>
  154.                     <button class="action-btn delete-btn">删除</button>
  155.                 </td>
  156.             </tr>
  157.         </tbody>
  158.     </table>
  159.     <script>
  160.         const employeeTable = document.getElementById('employeeTable');
  161.         const nameInput = document.getElementById('nameInput');
  162.         const positionInput = document.getElementById('positionInput');
  163.         const emailInput = document.getElementById('emailInput');
  164.         const addBtn = document.getElementById('addBtn');
  165.         const notification = document.getElementById('notification');
  166.         let nextId = 4;
  167.         
  168.         // 显示通知
  169.         function showNotification(message, type) {
  170.             notification.textContent = message;
  171.             notification.className = `notification ${type}`;
  172.             notification.style.display = 'block';
  173.             
  174.             setTimeout(() => {
  175.                 notification.style.display = 'none';
  176.             }, 3000);
  177.         }
  178.         
  179.         // 使用事件委托处理表格中的点击事件
  180.         employeeTable.addEventListener('click', function(event) {
  181.             const target = event.target;
  182.             
  183.             // 处理编辑按钮点击
  184.             if (target.classList.contains('edit-btn')) {
  185.                 const row = target.closest('tr');
  186.                 const cells = row.querySelectorAll('td');
  187.                
  188.                 // 检查是否已经在编辑模式
  189.                 if (target.textContent === '保存') {
  190.                     // 保存编辑
  191.                     const nameCell = cells[1];
  192.                     const positionCell = cells[2];
  193.                     const emailCell = cells[3];
  194.                     
  195.                     const nameInput = nameCell.querySelector('input');
  196.                     const positionInput = positionCell.querySelector('input');
  197.                     const emailInput = emailCell.querySelector('input');
  198.                     
  199.                     // 验证输入
  200.                     if (!nameInput.value.trim() || !positionInput.value.trim() || !emailInput.value.trim()) {
  201.                         showNotification('所有字段都必须填写', 'error');
  202.                         return;
  203.                     }
  204.                     
  205.                     // 更新单元格内容
  206.                     nameCell.textContent = nameInput.value;
  207.                     positionCell.textContent = positionInput.value;
  208.                     emailCell.textContent = emailInput.value;
  209.                     
  210.                     // 恢复按钮
  211.                     target.textContent = '编辑';
  212.                     target.className = 'action-btn edit-btn';
  213.                     row.querySelector('.cancel-btn').style.display = 'none';
  214.                     
  215.                     showNotification('员工信息已更新', 'success');
  216.                 } else {
  217.                     // 进入编辑模式
  218.                     const name = cells[1].textContent;
  219.                     const position = cells[2].textContent;
  220.                     const email = cells[3].textContent;
  221.                     
  222.                     // 替换单元格内容为输入框
  223.                     cells[1].innerHTML = `<input type="text" value="${name}">`;
  224.                     cells[2].innerHTML = `<input type="text" value="${position}">`;
  225.                     cells[3].innerHTML = `<input type="email" value="${email}">`;
  226.                     
  227.                     // 更改按钮
  228.                     target.textContent = '保存';
  229.                     target.className = 'action-btn save-btn';
  230.                     
  231.                     // 添加取消按钮
  232.                     const cancelBtn = document.createElement('button');
  233.                     cancelBtn.textContent = '取消';
  234.                     cancelBtn.className = 'action-btn cancel-btn';
  235.                     cells[4].appendChild(cancelBtn);
  236.                 }
  237.             }
  238.             
  239.             // 处理删除按钮点击
  240.             if (target.classList.contains('delete-btn')) {
  241.                 const row = target.closest('tr');
  242.                 const name = row.cells[1].textContent;
  243.                
  244.                 if (confirm(`确定要删除员工 ${name} 吗?`)) {
  245.                     row.remove();
  246.                     showNotification(`员工 ${name} 已被删除`, 'success');
  247.                 }
  248.             }
  249.             
  250.             // 处理取消按钮点击
  251.             if (target.classList.contains('cancel-btn')) {
  252.                 location.reload(); // 简单起见,重新加载页面
  253.             }
  254.         });
  255.         
  256.         // 添加新员工
  257.         addBtn.addEventListener('click', function() {
  258.             const name = nameInput.value.trim();
  259.             const position = positionInput.value.trim();
  260.             const email = emailInput.value.trim();
  261.             
  262.             // 验证输入
  263.             if (!name || !position || !email) {
  264.                 showNotification('所有字段都必须填写', 'error');
  265.                 return;
  266.             }
  267.             
  268.             // 创建新行
  269.             const newRow = document.createElement('tr');
  270.             newRow.setAttribute('data-id', nextId);
  271.             newRow.innerHTML = `
  272.                 <td>${nextId}</td>
  273.                 <td>${name}</td>
  274.                 <td>${position}</td>
  275.                 <td>${email}</td>
  276.                 <td>
  277.                     <button class="action-btn edit-btn">编辑</button>
  278.                     <button class="action-btn delete-btn">删除</button>
  279.                 </td>
  280.             `;
  281.             
  282.             // 添加到表格
  283.             employeeTable.querySelector('tbody').appendChild(newRow);
  284.             
  285.             // 清空输入框
  286.             nameInput.value = '';
  287.             positionInput.value = '';
  288.             emailInput.value = '';
  289.             
  290.             // 更新ID
  291.             nextId++;
  292.             
  293.             showNotification(`员工 ${name} 已添加`, 'success');
  294.         });
  295.         
  296.         // 支持按Enter键添加
  297.         [nameInput, positionInput, emailInput].forEach(input => {
  298.             input.addEventListener('keypress', function(event) {
  299.                 if (event.key === 'Enter') {
  300.                     addBtn.click();
  301.                 }
  302.             });
  303.         });
  304.     </script>
  305. </body>
  306. </html>
复制代码

这个动态表格操作示例展示了事件委托在实际应用中的强大功能。我们在表格的父元素上添加了一个事件监听器,处理所有编辑、删除和取消按钮的点击事件。这样,即使动态添加新的行,也不需要为它们单独添加事件监听器。

拖放功能实现
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>拖放功能实现</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 1000px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         
  15.         .container {
  16.             display: flex;
  17.             justify-content: space-between;
  18.             margin: 20px 0;
  19.         }
  20.         
  21.         .list {
  22.             width: 45%;
  23.             min-height: 300px;
  24.             border: 2px dashed #ccc;
  25.             border-radius: 5px;
  26.             padding: 10px;
  27.             background-color: #f9f9f9;
  28.         }
  29.         
  30.         .list-title {
  31.             text-align: center;
  32.             margin-bottom: 10px;
  33.             font-weight: bold;
  34.         }
  35.         
  36.         .item {
  37.             padding: 10px;
  38.             margin: 5px 0;
  39.             background-color: #fff;
  40.             border: 1px solid #ddd;
  41.             border-radius: 3px;
  42.             cursor: move;
  43.             transition: transform 0.2s;
  44.         }
  45.         
  46.         .item:hover {
  47.             transform: translateY(-2px);
  48.             box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  49.         }
  50.         
  51.         .item.dragging {
  52.             opacity: 0.5;
  53.         }
  54.         
  55.         .list.drag-over {
  56.             background-color: #e0f7fa;
  57.             border-color: #00bcd4;
  58.         }
  59.         
  60.         .notification {
  61.             padding: 10px;
  62.             margin: 10px 0;
  63.             border-radius: 3px;
  64.             display: none;
  65.         }
  66.         
  67.         .success {
  68.             background-color: #dff0d8;
  69.             color: #3c763d;
  70.             border: 1px solid #d6e9c6;
  71.         }
  72.         
  73.         .add-item {
  74.             display: flex;
  75.             margin: 20px 0;
  76.             gap: 10px;
  77.         }
  78.         
  79.         .add-item input {
  80.             flex-grow: 1;
  81.             padding: 8px;
  82.             border: 1px solid #ddd;
  83.             border-radius: 3px;
  84.         }
  85.         
  86.         .add-item button {
  87.             padding: 8px 15px;
  88.             background-color: #4CAF50;
  89.             color: white;
  90.             border: none;
  91.             border-radius: 3px;
  92.             cursor: pointer;
  93.         }
  94.     </style>
  95. </head>
  96. <body>
  97.     <h1>任务拖放管理</h1>
  98.    
  99.     <div class="notification" id="notification"></div>
  100.    
  101.     <div class="add-item">
  102.         <input type="text" id="newItemInput" placeholder="输入新任务">
  103.         <button id="addItemBtn">添加任务</button>
  104.     </div>
  105.    
  106.     <div class="container">
  107.         <div class="list" id="todoList">
  108.             <div class="list-title">待办事项</div>
  109.             <div class="item" draggable="true">完成项目报告</div>
  110.             <div class="item" draggable="true">准备会议材料</div>
  111.             <div class="item" draggable="true">回复客户邮件</div>
  112.         </div>
  113.         
  114.         <div class="list" id="doneList">
  115.             <div class="list-title">已完成</div>
  116.             <div class="item" draggable="true">更新网站内容</div>
  117.             <div class="item" draggable="true">修复登录问题</div>
  118.         </div>
  119.     </div>
  120.     <script>
  121.         const todoList = document.getElementById('todoList');
  122.         const doneList = document.getElementById('doneList');
  123.         const newItemInput = document.getElementById('newItemInput');
  124.         const addItemBtn = document.getElementById('addItemBtn');
  125.         const notification = document.getElementById('notification');
  126.         
  127.         // 显示通知
  128.         function showNotification(message) {
  129.             notification.textContent = message;
  130.             notification.className = 'notification success';
  131.             notification.style.display = 'block';
  132.             
  133.             setTimeout(() => {
  134.                 notification.style.display = 'none';
  135.             }, 3000);
  136.         }
  137.         
  138.         // 使用事件委托处理拖放事件
  139.         document.addEventListener('dragstart', function(event) {
  140.             if (event.target.classList.contains('item')) {
  141.                 event.target.classList.add('dragging');
  142.                 event.dataTransfer.effectAllowed = 'move';
  143.                 event.dataTransfer.setData('text/html', event.target.innerHTML);
  144.             }
  145.         });
  146.         
  147.         document.addEventListener('dragend', function(event) {
  148.             if (event.target.classList.contains('item')) {
  149.                 event.target.classList.remove('dragging');
  150.             }
  151.         });
  152.         
  153.         document.addEventListener('dragover', function(event) {
  154.             if (event.target.classList.contains('list')) {
  155.                 event.preventDefault();
  156.                 event.dataTransfer.dropEffect = 'move';
  157.             }
  158.         });
  159.         
  160.         document.addEventListener('dragenter', function(event) {
  161.             if (event.target.classList.contains('list')) {
  162.                 event.target.classList.add('drag-over');
  163.             }
  164.         });
  165.         
  166.         document.addEventListener('dragleave', function(event) {
  167.             if (event.target.classList.contains('list')) {
  168.                 event.target.classList.remove('drag-over');
  169.             }
  170.         });
  171.         
  172.         document.addEventListener('drop', function(event) {
  173.             if (event.target.classList.contains('list')) {
  174.                 event.preventDefault();
  175.                 event.target.classList.remove('drag-over');
  176.                
  177.                 const draggingItem = document.querySelector('.dragging');
  178.                 if (draggingItem) {
  179.                     const listTitle = event.target.querySelector('.list-title').textContent;
  180.                     const itemText = draggingItem.textContent;
  181.                     
  182.                     // 移动元素
  183.                     event.target.appendChild(draggingItem);
  184.                     
  185.                     // 显示通知
  186.                     showNotification(`任务"${itemText}"已移动到"${listTitle}"`);
  187.                 }
  188.             }
  189.         });
  190.         
  191.         // 添加新任务
  192.         addItemBtn.addEventListener('click', function() {
  193.             const itemText = newItemInput.value.trim();
  194.             if (!itemText) return;
  195.             
  196.             const newItem = document.createElement('div');
  197.             newItem.className = 'item';
  198.             newItem.draggable = true;
  199.             newItem.textContent = itemText;
  200.             
  201.             todoList.appendChild(newItem);
  202.             newItemInput.value = '';
  203.             
  204.             showNotification(`新任务"${itemText}"已添加`);
  205.         });
  206.         
  207.         // 支持按Enter键添加
  208.         newItemInput.addEventListener('keypress', function(event) {
  209.             if (event.key === 'Enter') {
  210.                 addItemBtn.click();
  211.             }
  212.         });
  213.     </script>
  214. </body>
  215. </html>
复制代码

这个拖放功能示例展示了如何使用HTML5的拖放API结合事件委托来实现一个任务管理界面。我们在document级别添加了拖放相关的事件监听器,通过检查event.target来确定事件源,从而实现了拖放功能。

总结

本文全面解析了HTML DOM事件监听的添加技巧,从基础的addEventListener方法到高级的事件委托技术。我们学习了:

1. addEventListener的基本用法:如何添加事件监听器,以及不同类型的事件处理函数。
2. 事件对象的详细解析:事件对象的属性和方法,以及如何利用它们获取事件相关信息。
3. 事件移除技术:如何使用removeEventListener移除不再需要的事件监听器。
4. 事件冒泡与捕获:理解事件流的三个阶段,以及如何控制事件的传播。
5. 事件委托技术:利用事件冒泡机制在父元素上处理子元素的事件,提高性能并简化代码。
6. 最佳实践与性能优化:包括事件节流、防抖等技术,以及如何优化事件处理性能。
7. 实际应用案例:通过动态表格操作和拖放功能等实例,展示了事件监听技术在实际开发中的应用。

掌握这些技术,可以帮助开发者创建出响应迅速、交互流畅的网页应用,提升用户体验。在实际开发中,应根据具体需求选择合适的事件处理方式,并注意性能优化,避免常见的问题。

随着Web技术的不断发展,事件处理也在不断演进。作为开发者,我们需要持续学习和实践,掌握最新的事件处理技术,以应对日益复杂的交互需求。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则