简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

JavaScript修改HTML DOM实战教程掌握动态网页开发的核心技能通过实际案例学习如何操作元素处理事件和更新页面内容

3万

主题

317

科技点

3万

积分

大区版主

木柜子打湿

积分
31893

财Doro三倍冰淇淋无人之境【一阶】立华奏小樱(小丑装)⑨的冰沙以外的星空【二阶】

发表于 2025-10-4 09:00:00 | 显示全部楼层 |阅读模式

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

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

x
引言

在现代Web开发中,JavaScript操作DOM(文档对象模型)是创建动态、交互式网页的核心技能。DOM是一个编程接口,允许JavaScript访问和修改HTML文档的内容、结构和样式。通过掌握DOM操作,开发者可以创建响应式用户界面、处理用户交互、动态更新页面内容,从而提升用户体验。本教程将通过实际案例,系统地介绍如何使用JavaScript操作DOM元素、处理事件和更新页面内容。

DOM基础

什么是DOM

DOM(Document Object Model)是HTML和XML文档的编程接口。它将文档表示为一个树状结构,其中每个节点都是文档中的一个对象(如元素、属性、文本等)。JavaScript可以通过DOM API访问和操作这些对象。
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>DOM示例</title>
  5. </head>
  6. <body>
  7.     <h1>欢迎学习DOM</h1>
  8.     <p>这是一个段落。</p>
  9. </body>
  10. </html>
复制代码

在上面的HTML文档中,DOM树结构如下:
  1. Document
  2. └── html
  3.      ├── head
  4.      │   └── title
  5.      │       └── "DOM示例"
  6.      └── body
  7.          ├── h1
  8.          │   └── "欢迎学习DOM"
  9.          └── p
  10.              └── "这是一个段落。"
复制代码

DOM的重要性

DOM操作的重要性体现在:

1. 动态内容更新:无需刷新页面即可更新内容
2. 用户交互响应:实时响应用户的操作
3. 创建丰富的用户体验:实现动画、拖放等复杂交互
4. 数据驱动的界面:根据数据动态渲染界面

选择DOM元素

在操作DOM之前,首先需要选择要操作的元素。JavaScript提供了多种选择元素的方法。

getElementById

通过元素的ID选择单个元素。
  1. <div id="myDiv">这是一个div元素</div>
  2. <script>
  3.     // 通过ID选择元素
  4.     const myDiv = document.getElementById('myDiv');
  5.     console.log(myDiv.textContent); // 输出: 这是一个div元素
  6. </script>
复制代码

getElementsByClassName

通过类名选择多个元素,返回一个HTMLCollection。
  1. <div class="box">盒子1</div>
  2. <div class="box">盒子2</div>
  3. <div class="box">盒子3</div>
  4. <script>
  5.     // 通过类名选择元素
  6.     const boxes = document.getElementsByClassName('box');
  7.     console.log(boxes.length); // 输出: 3
  8.    
  9.     // 遍历所有盒子
  10.     for (let i = 0; i < boxes.length; i++) {
  11.         console.log(boxes[i].textContent);
  12.     }
  13. </script>
复制代码

getElementsByTagName

通过标签名选择多个元素,返回一个HTMLCollection。
  1. <p>段落1</p>
  2. <p>段落2</p>
  3. <p>段落3</p>
  4. <script>
  5.     // 通过标签名选择元素
  6.     const paragraphs = document.getElementsByTagName('p');
  7.     console.log(paragraphs.length); // 输出: 3
  8. </script>
复制代码

querySelector和querySelectorAll

使用CSS选择器语法选择元素。querySelector返回第一个匹配的元素,querySelectorAll返回所有匹配的元素(NodeList)。
  1. <div id="container">
  2.     <p class="text">第一段</p>
  3.     <p class="text">第二段</p>
  4.     <div class="text">这是一个div</div>
  5. </div>
  6. <script>
  7.     // 使用querySelector选择第一个匹配的元素
  8.     const firstText = document.querySelector('#container .text');
  9.     console.log(firstText.textContent); // 输出: 第一段
  10.    
  11.     // 使用querySelectorAll选择所有匹配的元素
  12.     const allTexts = document.querySelectorAll('#container .text');
  13.     console.log(allTexts.length); // 输出: 3
  14.    
  15.     // 遍历所有元素
  16.     allTexts.forEach(element => {
  17.         console.log(element.textContent);
  18.     });
  19. </script>
复制代码

修改元素内容

修改文本内容

使用textContent或innerText属性修改元素的文本内容。
  1. <div id="textElement">原始文本</div>
  2. <button id="changeTextBtn">修改文本</button>
  3. <script>
  4.     const textElement = document.getElementById('textElement');
  5.     const changeTextBtn = document.getElementById('changeTextBtn');
  6.    
  7.     changeTextBtn.addEventListener('click', function() {
  8.         // 使用textContent修改文本
  9.         textElement.textContent = '文本已被修改';
  10.         
  11.         // 3秒后再次修改
  12.         setTimeout(() => {
  13.             // 使用innerText修改文本(与textContent类似,但会考虑CSS样式)
  14.             textElement.innerText = '再次修改的文本';
  15.         }, 3000);
  16.     });
  17. </script>
复制代码

修改HTML内容

使用innerHTML属性修改元素的HTML内容。
  1. <div id="htmlElement">
  2.     <p>原始HTML内容</p>
  3. </div>
  4. <button id="changeHtmlBtn">修改HTML</button>
  5. <script>
  6.     const htmlElement = document.getElementById('htmlElement');
  7.     const changeHtmlBtn = document.getElementById('changeHtmlBtn');
  8.    
  9.     changeHtmlBtn.addEventListener('click', function() {
  10.         // 使用innerHTML修改HTML内容
  11.         htmlElement.innerHTML = `
  12.             <ul>
  13.                 <li>列表项1</li>
  14.                 <li>列表项2</li>
  15.                 <li>列表项3</li>
  16.             </ul>
  17.         `;
  18.     });
  19. </script>
复制代码

注意:使用innerHTML存在安全风险,如果内容来自用户输入,可能导致XSS攻击。对于不受信任的内容,应使用textContent或其他安全方法。

修改元素属性

标准属性

可以直接通过点表示法或setAttribute方法修改元素的标准属性。
  1. <img id="myImage" src="image1.jpg" alt="图片1" width="200">
  2. <button id="changeAttrBtn">修改属性</button>
  3. <script>
  4.     const myImage = document.getElementById('myImage');
  5.     const changeAttrBtn = document.getElementById('changeAttrBtn');
  6.    
  7.     changeAttrBtn.addEventListener('click', function() {
  8.         // 使用点表示法修改属性
  9.         myImage.src = 'image2.jpg';
  10.         myImage.alt = '图片2';
  11.         
  12.         // 使用setAttribute方法修改属性
  13.         myImage.setAttribute('width', '300');
  14.     });
  15. </script>
复制代码

自定义属性(data-*)

HTML5允许使用data-*属性存储自定义数据。
  1. <div id="dataElement" data-user-id="123" data-role="admin">用户信息</div>
  2. <button id="showDataBtn">显示数据</button>
  3. <button id="changeDataBtn">修改数据</button>
  4. <script>
  5.     const dataElement = document.getElementById('dataElement');
  6.     const showDataBtn = document.getElementById('showDataBtn');
  7.     const changeDataBtn = document.getElementById('changeDataBtn');
  8.    
  9.     showDataBtn.addEventListener('click', function() {
  10.         // 使用dataset属性访问data-*属性
  11.         const userId = dataElement.dataset.userId;
  12.         const role = dataElement.dataset.role;
  13.         
  14.         alert(`用户ID: ${userId}, 角色: ${role}`);
  15.     });
  16.    
  17.     changeDataBtn.addEventListener('click', function() {
  18.         // 修改data-*属性
  19.         dataElement.dataset.userId = '456';
  20.         dataElement.dataset.role = 'user';
  21.         
  22.         alert('数据已修改');
  23.     });
  24. </script>
复制代码

修改元素样式

直接修改style属性

可以通过元素的style对象直接修改CSS样式。
  1. <div id="styleElement" style="width: 100px; height: 100px; background-color: blue;"></div>
  2. <button id="changeStyleBtn">修改样式</button>
  3. <script>
  4.     const styleElement = document.getElementById('styleElement');
  5.     const changeStyleBtn = document.getElementById('changeStyleBtn');
  6.    
  7.     changeStyleBtn.addEventListener('click', function() {
  8.         // 直接修改style属性
  9.         styleElement.style.backgroundColor = 'red';
  10.         styleElement.style.width = '200px';
  11.         styleElement.style.height = '200px';
  12.         styleElement.style.borderRadius = '50%';
  13.     });
  14. </script>
复制代码

注意:CSS属性名在JavaScript中通常使用驼峰命名法,例如backgroundColor代替background-color。

通过classList修改类名

使用classList属性添加、删除、切换或检查元素的类名。
  1. <style>
  2.     .box {
  3.         width: 100px;
  4.         height: 100px;
  5.         background-color: blue;
  6.         transition: all 0.3s ease;
  7.     }
  8.    
  9.     .highlight {
  10.         background-color: yellow;
  11.         border: 2px solid red;
  12.     }
  13.    
  14.     .rounded {
  15.         border-radius: 50%;
  16.     }
  17. </style>
  18. <div id="classElement" class="box"></div>
  19. <button id="addClassBtn">添加高亮</button>
  20. <button id="toggleClassBtn">切换圆角</button>
  21. <button id="removeClassBtn">移除高亮</button>
  22. <script>
  23.     const classElement = document.getElementById('classElement');
  24.     const addClassBtn = document.getElementById('addClassBtn');
  25.     const toggleClassBtn = document.getElementById('toggleClassBtn');
  26.     const removeClassBtn = document.getElementById('removeClassBtn');
  27.    
  28.     addClassBtn.addEventListener('click', function() {
  29.         // 添加类名
  30.         classElement.classList.add('highlight');
  31.     });
  32.    
  33.     toggleClassBtn.addEventListener('click', function() {
  34.         // 切换类名(如果存在则移除,不存在则添加)
  35.         classElement.classList.toggle('rounded');
  36.     });
  37.    
  38.     removeClassBtn.addEventListener('click', function() {
  39.         // 移除类名
  40.         classElement.classList.remove('highlight');
  41.     });
  42. </script>
复制代码

创建和删除元素

创建新元素

使用document.createElement方法创建新元素,然后使用appendChild或insertBefore将其添加到DOM中。
  1. <div id="container">
  2.     <p>原始段落</p>
  3. </div>
  4. <button id="addElementBtn">添加元素</button>
  5. <script>
  6.     const container = document.getElementById('container');
  7.     const addElementBtn = document.getElementById('addElementBtn');
  8.    
  9.     addElementBtn.addEventListener('click', function() {
  10.         // 创建新元素
  11.         const newParagraph = document.createElement('p');
  12.         
  13.         // 设置元素内容
  14.         newParagraph.textContent = '这是新添加的段落';
  15.         
  16.         // 添加样式
  17.         newParagraph.style.color = 'red';
  18.         newParagraph.style.fontWeight = 'bold';
  19.         
  20.         // 将新元素添加到容器中
  21.         container.appendChild(newParagraph);
  22.     });
  23. </script>
复制代码

删除元素

使用removeChild方法或remove方法删除元素。
  1. <div id="elementsContainer">
  2.     <div class="item">项目1 <button class="deleteBtn">删除</button></div>
  3.     <div class="item">项目2 <button class="deleteBtn">删除</button></div>
  4.     <div class="item">项目3 <button class="deleteBtn">删除</button></div>
  5. </div>
  6. <script>
  7.     const elementsContainer = document.getElementById('elementsContainer');
  8.    
  9.     // 使用事件委托处理删除按钮的点击事件
  10.     elementsContainer.addEventListener('click', function(event) {
  11.         // 检查点击的是否是删除按钮
  12.         if (event.target.classList.contains('deleteBtn')) {
  13.             // 获取要删除的项目
  14.             const itemToDelete = event.target.parentElement;
  15.             
  16.             // 从父元素中删除子元素
  17.             elementsContainer.removeChild(itemToDelete);
  18.             
  19.             // 或者直接使用remove方法
  20.             // itemToDelete.remove();
  21.         }
  22.     });
  23. </script>
复制代码

克隆元素

使用cloneNode方法克隆元素,参数true表示深度克隆(包括所有子元素)。
  1. <div id="original">
  2.     <h2>原始元素</h2>
  3.     <p>这是一个段落。</p>
  4. </div>
  5. <button id="cloneBtn">克隆元素</button>
  6. <div id="clonesContainer"></div>
  7. <script>
  8.     const original = document.getElementById('original');
  9.     const cloneBtn = document.getElementById('cloneBtn');
  10.     const clonesContainer = document.getElementById('clonesContainer');
  11.    
  12.     cloneBtn.addEventListener('click', function() {
  13.         // 深度克隆原始元素
  14.         const clonedElement = original.cloneNode(true);
  15.         
  16.         // 修改克隆元素的ID以避免重复
  17.         clonedElement.id = 'cloned-' + Date.now();
  18.         
  19.         // 将克隆元素添加到容器中
  20.         clonesContainer.appendChild(clonedElement);
  21.     });
  22. </script>
复制代码

事件处理

事件监听器

使用addEventListener方法为元素添加事件监听器。
  1. <button id="clickBtn">点击我</button>
  2. <div id="output"></div>
  3. <script>
  4.     const clickBtn = document.getElementById('clickBtn');
  5.     const output = document.getElementById('output');
  6.    
  7.     // 添加点击事件监听器
  8.     clickBtn.addEventListener('click', function() {
  9.         output.textContent = '按钮被点击了!';
  10.         output.style.color = 'green';
  11.     });
  12.    
  13.     // 添加鼠标悬停事件监听器
  14.     clickBtn.addEventListener('mouseover', function() {
  15.         this.style.backgroundColor = 'lightblue';
  16.     });
  17.    
  18.     // 添加鼠标离开事件监听器
  19.     clickBtn.addEventListener('mouseout', function() {
  20.         this.style.backgroundColor = '';
  21.     });
  22. </script>
复制代码

事件对象

事件处理函数接收一个事件对象,包含关于事件的详细信息。
  1. <div id="mouseArea" style="width: 300px; height: 200px; background-color: #f0f0f0; padding: 10px;">
  2.     在此区域移动鼠标
  3. </div>
  4. <div id="mouseInfo"></div>
  5. <script>
  6.     const mouseArea = document.getElementById('mouseArea');
  7.     const mouseInfo = document.getElementById('mouseInfo');
  8.    
  9.     mouseArea.addEventListener('mousemove', function(event) {
  10.         // 获取鼠标位置
  11.         const x = event.clientX;
  12.         const y = event.clientY;
  13.         
  14.         // 显示鼠标位置信息
  15.         mouseInfo.innerHTML = `
  16.             <p>鼠标位置: X=${x}, Y=${y}</p>
  17.             <p>相对于元素: X=${event.offsetX}, Y=${event.offsetY}</p>
  18.         `;
  19.     });
  20. </script>
复制代码

事件冒泡和捕获

事件在DOM中的传播分为三个阶段:捕获阶段、目标阶段和冒泡阶段。
  1. <style>
  2.     .outer {
  3.         width: 300px;
  4.         height: 300px;
  5.         background-color: #f0f0f0;
  6.         padding: 20px;
  7.     }
  8.    
  9.     .middle {
  10.         width: 200px;
  11.         height: 200px;
  12.         background-color: #d0d0d0;
  13.         padding: 20px;
  14.     }
  15.    
  16.     .inner {
  17.         width: 100px;
  18.         height: 100px;
  19.         background-color: #b0b0b0;
  20.         padding: 20px;
  21.     }
  22. </style>
  23. <div id="outer" class="outer">
  24.     外层元素
  25.     <div id="middle" class="middle">
  26.         中层元素
  27.         <div id="inner" class="inner">
  28.             内层元素
  29.         </div>
  30.     </div>
  31. </div>
  32. <div id="eventLog"></div>
  33. <script>
  34.     const outer = document.getElementById('outer');
  35.     const middle = document.getElementById('middle');
  36.     const inner = document.getElementById('inner');
  37.     const eventLog = document.getElementById('eventLog');
  38.    
  39.     // 添加点击事件监听器(冒泡阶段)
  40.     outer.addEventListener('click', function(event) {
  41.         logEvent('外层元素 - 冒泡阶段');
  42.     });
  43.    
  44.     middle.addEventListener('click', function(event) {
  45.         logEvent('中层元素 - 冒泡阶段');
  46.     });
  47.    
  48.     inner.addEventListener('click', function(event) {
  49.         logEvent('内层元素 - 冒泡阶段');
  50.     });
  51.    
  52.     // 添加点击事件监听器(捕获阶段)
  53.     outer.addEventListener('click', function(event) {
  54.         logEvent('外层元素 - 捕获阶段');
  55.     }, true);
  56.    
  57.     middle.addEventListener('click', function(event) {
  58.         logEvent('中层元素 - 捕获阶段');
  59.     }, true);
  60.    
  61.     inner.addEventListener('click', function(event) {
  62.         logEvent('内层元素 - 捕获阶段');
  63.     }, true);
  64.    
  65.     function logEvent(message) {
  66.         const p = document.createElement('p');
  67.         p.textContent = message;
  68.         eventLog.appendChild(p);
  69.     }
  70. </script>
复制代码

事件委托

利用事件冒泡机制,在父元素上处理子元素的事件。
  1. <ul id="itemList">
  2.     <li data-id="1">项目1</li>
  3.     <li data-id="2">项目2</li>
  4.     <li data-id="3">项目3</li>
  5. </ul>
  6. <button id="addItemBtn">添加项目</button>
  7. <div id="selectedItem"></div>
  8. <script>
  9.     const itemList = document.getElementById('itemList');
  10.     const addItemBtn = document.getElementById('addItemBtn');
  11.     const selectedItem = document.getElementById('selectedItem');
  12.     let itemCount = 3;
  13.    
  14.     // 使用事件委托处理列表项的点击事件
  15.     itemList.addEventListener('click', function(event) {
  16.         // 检查点击的是否是列表项
  17.         if (event.target.tagName === 'LI') {
  18.             // 获取项目ID
  19.             const itemId = event.target.dataset.id;
  20.             
  21.             // 显示选中的项目
  22.             selectedItem.textContent = `选中的项目ID: ${itemId}, 内容: ${event.target.textContent}`;
  23.             
  24.             // 高亮选中的项目
  25.             // 移除所有项目的高亮
  26.             document.querySelectorAll('#itemList li').forEach(li => {
  27.                 li.style.backgroundColor = '';
  28.             });
  29.             
  30.             // 高亮当前项目
  31.             event.target.style.backgroundColor = 'lightblue';
  32.         }
  33.     });
  34.    
  35.     // 添加新项目
  36.     addItemBtn.addEventListener('click', function() {
  37.         itemCount++;
  38.         const newItem = document.createElement('li');
  39.         newItem.dataset.id = itemCount;
  40.         newItem.textContent = `项目${itemCount}`;
  41.         itemList.appendChild(newItem);
  42.     });
  43. </script>
复制代码

实战案例

动态待办事项列表

创建一个可以添加、删除和标记完成状态的待办事项列表。
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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: 600px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         
  15.         h1 {
  16.             text-align: center;
  17.             color: #333;
  18.         }
  19.         
  20.         .input-container {
  21.             display: flex;
  22.             margin-bottom: 20px;
  23.         }
  24.         
  25.         #todoInput {
  26.             flex: 1;
  27.             padding: 10px;
  28.             border: 1px solid #ddd;
  29.             border-radius: 4px;
  30.             font-size: 16px;
  31.         }
  32.         
  33.         #addBtn {
  34.             padding: 10px 15px;
  35.             background-color: #4CAF50;
  36.             color: white;
  37.             border: none;
  38.             border-radius: 4px;
  39.             margin-left: 10px;
  40.             cursor: pointer;
  41.             font-size: 16px;
  42.         }
  43.         
  44.         #addBtn:hover {
  45.             background-color: #45a049;
  46.         }
  47.         
  48.         #todoList {
  49.             list-style: none;
  50.             padding: 0;
  51.         }
  52.         
  53.         .todo-item {
  54.             display: flex;
  55.             align-items: center;
  56.             padding: 12px;
  57.             border-bottom: 1px solid #eee;
  58.         }
  59.         
  60.         .todo-item:last-child {
  61.             border-bottom: none;
  62.         }
  63.         
  64.         .todo-text {
  65.             flex: 1;
  66.             margin-left: 10px;
  67.         }
  68.         
  69.         .completed {
  70.             text-decoration: line-through;
  71.             color: #888;
  72.         }
  73.         
  74.         .delete-btn {
  75.             background-color: #f44336;
  76.             color: white;
  77.             border: none;
  78.             border-radius: 4px;
  79.             padding: 5px 10px;
  80.             cursor: pointer;
  81.         }
  82.         
  83.         .delete-btn:hover {
  84.             background-color: #d32f2f;
  85.         }
  86.         
  87.         .empty-state {
  88.             text-align: center;
  89.             color: #888;
  90.             padding: 20px;
  91.         }
  92.     </style>
  93. </head>
  94. <body>
  95.     <h1>待办事项列表</h1>
  96.    
  97.     <div class="input-container">
  98.         <input type="text" id="todoInput" placeholder="添加新的待办事项...">
  99.         <button id="addBtn">添加</button>
  100.     </div>
  101.    
  102.     <ul id="todoList">
  103.         <li class="empty-state">暂无待办事项,请添加新的项目</li>
  104.     </ul>
  105.     <script>
  106.         // 获取DOM元素
  107.         const todoInput = document.getElementById('todoInput');
  108.         const addBtn = document.getElementById('addBtn');
  109.         const todoList = document.getElementById('todoList');
  110.         
  111.         // 初始化待办事项数组
  112.         let todos = [];
  113.         
  114.         // 添加待办事项
  115.         function addTodo() {
  116.             const todoText = todoInput.value.trim();
  117.             
  118.             if (todoText === '') {
  119.                 alert('请输入待办事项内容');
  120.                 return;
  121.             }
  122.             
  123.             // 创建新的待办事项对象
  124.             const newTodo = {
  125.                 id: Date.now(),
  126.                 text: todoText,
  127.                 completed: false
  128.             };
  129.             
  130.             // 添加到数组
  131.             todos.push(newTodo);
  132.             
  133.             // 清空输入框
  134.             todoInput.value = '';
  135.             
  136.             // 渲染列表
  137.             renderTodos();
  138.         }
  139.         
  140.         // 删除待办事项
  141.         function deleteTodo(id) {
  142.             // 从数组中过滤掉要删除的项目
  143.             todos = todos.filter(todo => todo.id !== id);
  144.             
  145.             // 渲染列表
  146.             renderTodos();
  147.         }
  148.         
  149.         // 切换待办事项完成状态
  150.         function toggleTodo(id) {
  151.             // 查找并更新待办事项
  152.             todos = todos.map(todo => {
  153.                 if (todo.id === id) {
  154.                     return { ...todo, completed: !todo.completed };
  155.                 }
  156.                 return todo;
  157.             });
  158.             
  159.             // 渲染列表
  160.             renderTodos();
  161.         }
  162.         
  163.         // 渲染待办事项列表
  164.         function renderTodos() {
  165.             // 清空列表
  166.             todoList.innerHTML = '';
  167.             
  168.             // 检查是否有待办事项
  169.             if (todos.length === 0) {
  170.                 const emptyState = document.createElement('li');
  171.                 emptyState.className = 'empty-state';
  172.                 emptyState.textContent = '暂无待办事项,请添加新的项目';
  173.                 todoList.appendChild(emptyState);
  174.                 return;
  175.             }
  176.             
  177.             // 为每个待办事项创建列表项
  178.             todos.forEach(todo => {
  179.                 const li = document.createElement('li');
  180.                 li.className = 'todo-item';
  181.                
  182.                 // 创建复选框
  183.                 const checkbox = document.createElement('input');
  184.                 checkbox.type = 'checkbox';
  185.                 checkbox.checked = todo.completed;
  186.                 checkbox.addEventListener('change', () => toggleTodo(todo.id));
  187.                
  188.                 // 创建文本元素
  189.                 const text = document.createElement('span');
  190.                 text.className = 'todo-text';
  191.                 text.textContent = todo.text;
  192.                 if (todo.completed) {
  193.                     text.classList.add('completed');
  194.                 }
  195.                
  196.                 // 创建删除按钮
  197.                 const deleteBtn = document.createElement('button');
  198.                 deleteBtn.className = 'delete-btn';
  199.                 deleteBtn.textContent = '删除';
  200.                 deleteBtn.addEventListener('click', () => deleteTodo(todo.id));
  201.                
  202.                 // 添加元素到列表项
  203.                 li.appendChild(checkbox);
  204.                 li.appendChild(text);
  205.                 li.appendChild(deleteBtn);
  206.                
  207.                 // 添加列表项到列表
  208.                 todoList.appendChild(li);
  209.             });
  210.         }
  211.         
  212.         // 添加事件监听器
  213.         addBtn.addEventListener('click', addTodo);
  214.         
  215.         // 按Enter键添加待办事项
  216.         todoInput.addEventListener('keypress', function(event) {
  217.             if (event.key === 'Enter') {
  218.                 addTodo();
  219.             }
  220.         });
  221.         
  222.         // 初始渲染
  223.         renderTodos();
  224.     </script>
  225. </body>
  226. </html>
复制代码

动态表单生成器

创建一个可以动态添加和删除表单字段的表单生成器。
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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.         h1 {
  16.             text-align: center;
  17.             color: #333;
  18.         }
  19.         
  20.         .form-builder {
  21.             margin-bottom: 30px;
  22.             padding: 20px;
  23.             border: 1px solid #ddd;
  24.             border-radius: 5px;
  25.             background-color: #f9f9f9;
  26.         }
  27.         
  28.         .field-controls {
  29.             margin-bottom: 15px;
  30.         }
  31.         
  32.         .field-controls select,
  33.         .field-controls input {
  34.             padding: 8px;
  35.             margin-right: 10px;
  36.             border: 1px solid #ddd;
  37.             border-radius: 4px;
  38.         }
  39.         
  40.         .add-field-btn {
  41.             padding: 8px 15px;
  42.             background-color: #4CAF50;
  43.             color: white;
  44.             border: none;
  45.             border-radius: 4px;
  46.             cursor: pointer;
  47.         }
  48.         
  49.         .add-field-btn:hover {
  50.             background-color: #45a049;
  51.         }
  52.         
  53.         .form-preview {
  54.             padding: 20px;
  55.             border: 1px solid #ddd;
  56.             border-radius: 5px;
  57.             background-color: #fff;
  58.         }
  59.         
  60.         .form-field {
  61.             margin-bottom: 15px;
  62.         }
  63.         
  64.         .form-field label {
  65.             display: block;
  66.             margin-bottom: 5px;
  67.             font-weight: bold;
  68.         }
  69.         
  70.         .form-field input,
  71.         .form-field textarea,
  72.         .form-field select {
  73.             width: 100%;
  74.             padding: 8px;
  75.             box-sizing: border-box;
  76.             border: 1px solid #ddd;
  77.             border-radius: 4px;
  78.         }
  79.         
  80.         .form-field textarea {
  81.             resize: vertical;
  82.             min-height: 100px;
  83.         }
  84.         
  85.         .field-actions {
  86.             margin-top: 5px;
  87.         }
  88.         
  89.         .remove-field-btn {
  90.             padding: 5px 10px;
  91.             background-color: #f44336;
  92.             color: white;
  93.             border: none;
  94.             border-radius: 4px;
  95.             cursor: pointer;
  96.             font-size: 12px;
  97.         }
  98.         
  99.         .remove-field-btn:hover {
  100.             background-color: #d32f2f;
  101.         }
  102.         
  103.         .form-actions {
  104.             margin-top: 20px;
  105.             text-align: right;
  106.         }
  107.         
  108.         .submit-btn {
  109.             padding: 10px 20px;
  110.             background-color: #2196F3;
  111.             color: white;
  112.             border: none;
  113.             border-radius: 4px;
  114.             cursor: pointer;
  115.             font-size: 16px;
  116.         }
  117.         
  118.         .submit-btn:hover {
  119.             background-color: #0b7dda;
  120.         }
  121.         
  122.         .form-data {
  123.             margin-top: 30px;
  124.             padding: 15px;
  125.             border: 1px solid #ddd;
  126.             border-radius: 5px;
  127.             background-color: #f9f9f9;
  128.             display: none;
  129.         }
  130.         
  131.         .form-data h3 {
  132.             margin-top: 0;
  133.         }
  134.         
  135.         .form-data pre {
  136.             background-color: #eee;
  137.             padding: 10px;
  138.             border-radius: 4px;
  139.             white-space: pre-wrap;
  140.         }
  141.     </style>
  142. </head>
  143. <body>
  144.     <h1>动态表单生成器</h1>
  145.    
  146.     <div class="form-builder">
  147.         <h2>表单构建器</h2>
  148.         <div class="field-controls">
  149.             <select id="fieldType">
  150.                 <option value="text">文本输入</option>
  151.                 <option value="email">邮箱</option>
  152.                 <option value="password">密码</option>
  153.                 <option value="number">数字</option>
  154.                 <option value="textarea">文本区域</option>
  155.                 <option value="select">下拉选择</option>
  156.                 <option value="checkbox">复选框</option>
  157.                 <option value="radio">单选按钮</option>
  158.             </select>
  159.             <input type="text" id="fieldLabel" placeholder="字段标签">
  160.             <input type="text" id="fieldName" placeholder="字段名称">
  161.             <button id="addFieldBtn" class="add-field-btn">添加字段</button>
  162.         </div>
  163.     </div>
  164.    
  165.     <div class="form-preview">
  166.         <h2>表单预览</h2>
  167.         <form id="dynamicForm">
  168.             <!-- 动态生成的表单字段将在这里显示 -->
  169.         </form>
  170.         <div class="form-actions">
  171.             <button type="button" id="submitBtn" class="submit-btn">提交表单</button>
  172.         </div>
  173.     </div>
  174.    
  175.     <div id="formData" class="form-data">
  176.         <h3>表单数据</h3>
  177.         <pre id="formDataOutput"></pre>
  178.     </div>
  179.     <script>
  180.         // 获取DOM元素
  181.         const fieldType = document.getElementById('fieldType');
  182.         const fieldLabel = document.getElementById('fieldLabel');
  183.         const fieldName = document.getElementById('fieldName');
  184.         const addFieldBtn = document.getElementById('addFieldBtn');
  185.         const dynamicForm = document.getElementById('dynamicForm');
  186.         const submitBtn = document.getElementById('submitBtn');
  187.         const formData = document.getElementById('formData');
  188.         const formDataOutput = document.getElementById('formDataOutput');
  189.         
  190.         // 存储表单字段
  191.         let formFields = [];
  192.         
  193.         // 添加表单字段
  194.         function addFormField() {
  195.             const type = fieldType.value;
  196.             const label = fieldLabel.value.trim();
  197.             const name = fieldName.value.trim();
  198.             
  199.             if (label === '' || name === '') {
  200.                 alert('请填写字段标签和名称');
  201.                 return;
  202.             }
  203.             
  204.             // 创建字段对象
  205.             const field = {
  206.                 id: Date.now(),
  207.                 type: type,
  208.                 label: label,
  209.                 name: name,
  210.                 options: type === 'select' || type === 'radio' ? getOptions() : []
  211.             };
  212.             
  213.             // 添加到字段数组
  214.             formFields.push(field);
  215.             
  216.             // 清空输入
  217.             fieldLabel.value = '';
  218.             fieldName.value = '';
  219.             
  220.             // 渲染表单
  221.             renderForm();
  222.         }
  223.         
  224.         // 获取选项(用于下拉选择、单选按钮等)
  225.         function getOptions() {
  226.             const options = [];
  227.             const optionCount = prompt('请输入选项数量:', '3');
  228.             
  229.             if (optionCount && !isNaN(optionCount)) {
  230.                 const count = parseInt(optionCount);
  231.                 for (let i = 0; i < count; i++) {
  232.                     const optionValue = prompt(`请输入选项 ${i + 1} 的值:`, `选项 ${i + 1}`);
  233.                     if (optionValue) {
  234.                         options.push(optionValue);
  235.                     }
  236.                 }
  237.             }
  238.             
  239.             return options;
  240.         }
  241.         
  242.         // 删除表单字段
  243.         function removeFormField(id) {
  244.             formFields = formFields.filter(field => field.id !== id);
  245.             renderForm();
  246.         }
  247.         
  248.         // 渲染表单
  249.         function renderForm() {
  250.             // 清空表单
  251.             dynamicForm.innerHTML = '';
  252.             
  253.             // 检查是否有字段
  254.             if (formFields.length === 0) {
  255.                 const emptyMessage = document.createElement('p');
  256.                 emptyMessage.textContent = '暂无表单字段,请添加字段';
  257.                 emptyMessage.style.textAlign = 'center';
  258.                 emptyMessage.style.color = '#888';
  259.                 dynamicForm.appendChild(emptyMessage);
  260.                 return;
  261.             }
  262.             
  263.             // 为每个字段创建表单元素
  264.             formFields.forEach(field => {
  265.                 const fieldDiv = document.createElement('div');
  266.                 fieldDiv.className = 'form-field';
  267.                
  268.                 // 创建标签
  269.                 const label = document.createElement('label');
  270.                 label.textContent = field.label;
  271.                 fieldDiv.appendChild(label);
  272.                
  273.                 // 根据字段类型创建不同的输入元素
  274.                 let inputElement;
  275.                
  276.                 switch (field.type) {
  277.                     case 'textarea':
  278.                         inputElement = document.createElement('textarea');
  279.                         inputElement.name = field.name;
  280.                         break;
  281.                         
  282.                     case 'select':
  283.                         inputElement = document.createElement('select');
  284.                         inputElement.name = field.name;
  285.                         
  286.                         // 添加默认选项
  287.                         const defaultOption = document.createElement('option');
  288.                         defaultOption.value = '';
  289.                         defaultOption.textContent = '请选择...';
  290.                         inputElement.appendChild(defaultOption);
  291.                         
  292.                         // 添加用户定义的选项
  293.                         field.options.forEach(option => {
  294.                             const optionElement = document.createElement('option');
  295.                             optionElement.value = option;
  296.                             optionElement.textContent = option;
  297.                             inputElement.appendChild(optionElement);
  298.                         });
  299.                         break;
  300.                         
  301.                     case 'checkbox':
  302.                         inputElement = document.createElement('input');
  303.                         inputElement.type = 'checkbox';
  304.                         inputElement.name = field.name;
  305.                         inputElement.value = 'yes';
  306.                         break;
  307.                         
  308.                     case 'radio':
  309.                         // 为单选按钮创建一个容器
  310.                         const radioContainer = document.createElement('div');
  311.                         
  312.                         field.options.forEach((option, index) => {
  313.                             const radioDiv = document.createElement('div');
  314.                             radioDiv.style.marginBottom = '5px';
  315.                            
  316.                             const radio = document.createElement('input');
  317.                             radio.type = 'radio';
  318.                             radio.name = field.name;
  319.                             radio.value = option;
  320.                             radio.id = `${field.name}_${index}`;
  321.                            
  322.                             const radioLabel = document.createElement('label');
  323.                             radioLabel.textContent = option;
  324.                             radioLabel.htmlFor = `${field.name}_${index}`;
  325.                             radioLabel.style.marginLeft = '5px';
  326.                             radioLabel.style.fontWeight = 'normal';
  327.                            
  328.                             radioDiv.appendChild(radio);
  329.                             radioDiv.appendChild(radioLabel);
  330.                             radioContainer.appendChild(radioDiv);
  331.                         });
  332.                         
  333.                         fieldDiv.appendChild(radioContainer);
  334.                         break;
  335.                         
  336.                     default:
  337.                         inputElement = document.createElement('input');
  338.                         inputElement.type = field.type;
  339.                         inputElement.name = field.name;
  340.                 }
  341.                
  342.                 // 如果不是单选按钮,添加输入元素
  343.                 if (field.type !== 'radio') {
  344.                     fieldDiv.appendChild(inputElement);
  345.                 }
  346.                
  347.                 // 添加删除按钮
  348.                 const actionsDiv = document.createElement('div');
  349.                 actionsDiv.className = 'field-actions';
  350.                
  351.                 const removeBtn = document.createElement('button');
  352.                 removeBtn.type = 'button';
  353.                 removeBtn.className = 'remove-field-btn';
  354.                 removeBtn.textContent = '删除字段';
  355.                 removeBtn.addEventListener('click', () => removeFormField(field.id));
  356.                
  357.                 actionsDiv.appendChild(removeBtn);
  358.                 fieldDiv.appendChild(actionsDiv);
  359.                
  360.                 // 添加字段到表单
  361.                 dynamicForm.appendChild(fieldDiv);
  362.             });
  363.         }
  364.         
  365.         // 提交表单
  366.         function submitForm() {
  367.             if (formFields.length === 0) {
  368.                 alert('表单没有字段,无法提交');
  369.                 return;
  370.             }
  371.             
  372.             // 创建FormData对象
  373.             const formData = new FormData(dynamicForm);
  374.             
  375.             // 转换为普通对象
  376.             const formDataObj = {};
  377.             
  378.             // 处理常规字段
  379.             for (let [key, value] of formData.entries()) {
  380.                 // 如果字段已存在,转换为数组
  381.                 if (formDataObj[key]) {
  382.                     if (!Array.isArray(formDataObj[key])) {
  383.                         formDataObj[key] = [formDataObj[key]];
  384.                     }
  385.                     formDataObj[key].push(value);
  386.                 } else {
  387.                     formDataObj[key] = value;
  388.                 }
  389.             }
  390.             
  391.             // 处理复选框(如果未选中,不会包含在FormData中)
  392.             formFields.forEach(field => {
  393.                 if (field.type === 'checkbox' && !formDataObj[field.name]) {
  394.                     formDataObj[field.name] = 'no';
  395.                 }
  396.             });
  397.             
  398.             // 显示表单数据
  399.             formData.style.display = 'block';
  400.             formDataOutput.textContent = JSON.stringify(formDataObj, null, 2);
  401.         }
  402.         
  403.         // 添加事件监听器
  404.         addFieldBtn.addEventListener('click', addFormField);
  405.         submitBtn.addEventListener('click', submitForm);
  406.         
  407.         // 初始渲染
  408.         renderForm();
  409.     </script>
  410. </body>
  411. </html>
复制代码

实时搜索过滤器

创建一个实时搜索过滤器,可以根据用户输入过滤列表项。
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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.         h1 {
  16.             text-align: center;
  17.             color: #333;
  18.         }
  19.         
  20.         .search-container {
  21.             margin-bottom: 20px;
  22.         }
  23.         
  24.         #searchInput {
  25.             width: 100%;
  26.             padding: 12px;
  27.             border: 1px solid #ddd;
  28.             border-radius: 4px;
  29.             font-size: 16px;
  30.             box-sizing: border-box;
  31.         }
  32.         
  33.         .filter-options {
  34.             margin: 15px 0;
  35.             display: flex;
  36.             flex-wrap: wrap;
  37.             gap: 10px;
  38.         }
  39.         
  40.         .filter-option {
  41.             display: flex;
  42.             align-items: center;
  43.         }
  44.         
  45.         .filter-option input {
  46.             margin-right: 5px;
  47.         }
  48.         
  49.         .item-list {
  50.             list-style: none;
  51.             padding: 0;
  52.         }
  53.         
  54.         .item {
  55.             padding: 15px;
  56.             border-bottom: 1px solid #eee;
  57.             display: flex;
  58.             align-items: center;
  59.         }
  60.         
  61.         .item:last-child {
  62.             border-bottom: none;
  63.         }
  64.         
  65.         .item-icon {
  66.             width: 50px;
  67.             height: 50px;
  68.             border-radius: 50%;
  69.             background-color: #4CAF50;
  70.             color: white;
  71.             display: flex;
  72.             align-items: center;
  73.             justify-content: center;
  74.             font-weight: bold;
  75.             margin-right: 15px;
  76.             flex-shrink: 0;
  77.         }
  78.         
  79.         .item-content {
  80.             flex: 1;
  81.         }
  82.         
  83.         .item-title {
  84.             font-weight: bold;
  85.             margin-bottom: 5px;
  86.         }
  87.         
  88.         .item-description {
  89.             color: #666;
  90.             font-size: 14px;
  91.         }
  92.         
  93.         .item-category {
  94.             display: inline-block;
  95.             padding: 3px 8px;
  96.             background-color: #e0e0e0;
  97.             border-radius: 12px;
  98.             font-size: 12px;
  99.             margin-top: 5px;
  100.         }
  101.         
  102.         .no-results {
  103.             text-align: center;
  104.             padding: 30px;
  105.             color: #888;
  106.             font-style: italic;
  107.         }
  108.         
  109.         .highlight {
  110.             background-color: yellow;
  111.             font-weight: bold;
  112.         }
  113.         
  114.         .stats {
  115.             margin-top: 20px;
  116.             padding: 10px;
  117.             background-color: #f5f5f5;
  118.             border-radius: 4px;
  119.             text-align: center;
  120.         }
  121.     </style>
  122. </head>
  123. <body>
  124.     <h1>实时搜索过滤器</h1>
  125.    
  126.     <div class="search-container">
  127.         <input type="text" id="searchInput" placeholder="搜索项目...">
  128.     </div>
  129.    
  130.     <div class="filter-options">
  131.         <div class="filter-option">
  132.             <input type="checkbox" id="filterFruits" value="水果" checked>
  133.             <label for="filterFruits">水果</label>
  134.         </div>
  135.         <div class="filter-option">
  136.             <input type="checkbox" id="filterVegetables" value="蔬菜" checked>
  137.             <label for="filterVegetables">蔬菜</label>
  138.         </div>
  139.         <div class="filter-option">
  140.             <input type="checkbox" id="filterGrains" value="谷物" checked>
  141.             <label for="filterGrains">谷物</label>
  142.         </div>
  143.         <div class="filter-option">
  144.             <input type="checkbox" id="filterProteins" value="蛋白质" checked>
  145.             <label for="filterProteins">蛋白质</label>
  146.         </div>
  147.     </div>
  148.    
  149.     <ul id="itemList" class="item-list">
  150.         <!-- 项目将通过JavaScript动态生成 -->
  151.     </ul>
  152.    
  153.     <div id="stats" class="stats">
  154.         显示 0 / 0 个项目
  155.     </div>
  156.     <script>
  157.         // 示例数据
  158.         const items = [
  159.             { id: 1, title: '苹果', description: '富含维生素C和纤维的水果', category: '水果' },
  160.             { id: 2, title: '香蕉', description: '富含钾的热带水果', category: '水果' },
  161.             { id: 3, title: '橙子', description: '富含维生素C的柑橘类水果', category: '水果' },
  162.             { id: 4, title: '草莓', description: '富含抗氧化剂的浆果', category: '水果' },
  163.             { id: 5, title: '胡萝卜', description: '富含维生素A的根茎蔬菜', category: '蔬菜' },
  164.             { id: 6, title: '西兰花', description: '富含维生素K和C的绿色蔬菜', category: '蔬菜' },
  165.             { id: 7, title: '菠菜', description: '富含铁和叶酸的绿叶蔬菜', category: '蔬菜' },
  166.             { id: 8, title: '番茄', description: '富含番茄红素的红色蔬果', category: '蔬菜' },
  167.             { id: 9, title: '大米', description: '主要的主食谷物', category: '谷物' },
  168.             { id: 10, title: '小麦', description: '制作面包和面食的谷物', category: '谷物' },
  169.             { id: 11, title: '燕麦', description: '富含可溶性纤维的谷物', category: '谷物' },
  170.             { id: 12, title: '玉米', description: '多用途的谷物', category: '谷物' },
  171.             { id: 13, title: '鸡肉', description: '优质蛋白质来源', category: '蛋白质' },
  172.             { id: 14, title: '鱼类', description: '富含Omega-3脂肪酸的蛋白质', category: '蛋白质' },
  173.             { id: 15, title: '豆腐', description: '植物性蛋白质来源', category: '蛋白质' },
  174.             { id: 16, title: '鸡蛋', description: '完整蛋白质来源', category: '蛋白质' }
  175.         ];
  176.         
  177.         // 获取DOM元素
  178.         const searchInput = document.getElementById('searchInput');
  179.         const filterOptions = document.querySelectorAll('.filter-option input');
  180.         const itemList = document.getElementById('itemList');
  181.         const stats = document.getElementById('stats');
  182.         
  183.         // 获取选中的类别
  184.         function getSelectedCategories() {
  185.             const selectedCategories = [];
  186.             filterOptions.forEach(option => {
  187.                 if (option.checked) {
  188.                     selectedCategories.push(option.value);
  189.                 }
  190.             });
  191.             return selectedCategories;
  192.         }
  193.         
  194.         // 高亮匹配的文本
  195.         function highlightText(text, searchTerm) {
  196.             if (!searchTerm) return text;
  197.             
  198.             const regex = new RegExp(`(${searchTerm})`, 'gi');
  199.             return text.replace(regex, '<span class="highlight">$1</span>');
  200.         }
  201.         
  202.         // 渲染项目列表
  203.         function renderItems() {
  204.             const searchTerm = searchInput.value.trim().toLowerCase();
  205.             const selectedCategories = getSelectedCategories();
  206.             
  207.             // 过滤项目
  208.             const filteredItems = items.filter(item => {
  209.                 // 检查类别是否被选中
  210.                 if (!selectedCategories.includes(item.category)) {
  211.                     return false;
  212.                 }
  213.                
  214.                 // 检查是否匹配搜索词
  215.                 if (searchTerm) {
  216.                     const titleMatch = item.title.toLowerCase().includes(searchTerm);
  217.                     const descriptionMatch = item.description.toLowerCase().includes(searchTerm);
  218.                     return titleMatch || descriptionMatch;
  219.                 }
  220.                
  221.                 return true;
  222.             });
  223.             
  224.             // 清空列表
  225.             itemList.innerHTML = '';
  226.             
  227.             // 检查是否有结果
  228.             if (filteredItems.length === 0) {
  229.                 const noResults = document.createElement('li');
  230.                 noResults.className = 'no-results';
  231.                 noResults.textContent = '没有找到匹配的项目';
  232.                 itemList.appendChild(noResults);
  233.             } else {
  234.                 // 渲染每个项目
  235.                 filteredItems.forEach(item => {
  236.                     const li = document.createElement('li');
  237.                     li.className = 'item';
  238.                     
  239.                     // 创建图标(使用首字母)
  240.                     const icon = document.createElement('div');
  241.                     icon.className = 'item-icon';
  242.                     icon.textContent = item.title.charAt(0);
  243.                     
  244.                     // 根据类别设置不同的背景色
  245.                     switch (item.category) {
  246.                         case '水果':
  247.                             icon.style.backgroundColor = '#FF9800';
  248.                             break;
  249.                         case '蔬菜':
  250.                             icon.style.backgroundColor = '#4CAF50';
  251.                             break;
  252.                         case '谷物':
  253.                             icon.style.backgroundColor = '#FFC107';
  254.                             break;
  255.                         case '蛋白质':
  256.                             icon.style.backgroundColor = '#F44336';
  257.                             break;
  258.                     }
  259.                     
  260.                     // 创建内容区域
  261.                     const content = document.createElement('div');
  262.                     content.className = 'item-content';
  263.                     
  264.                     // 创建标题(高亮匹配的文本)
  265.                     const title = document.createElement('div');
  266.                     title.className = 'item-title';
  267.                     title.innerHTML = highlightText(item.title, searchTerm);
  268.                     
  269.                     // 创建描述(高亮匹配的文本)
  270.                     const description = document.createElement('div');
  271.                     description.className = 'item-description';
  272.                     description.innerHTML = highlightText(item.description, searchTerm);
  273.                     
  274.                     // 创建类别标签
  275.                     const category = document.createElement('div');
  276.                     category.className = 'item-category';
  277.                     category.textContent = item.category;
  278.                     
  279.                     // 组装内容
  280.                     content.appendChild(title);
  281.                     content.appendChild(description);
  282.                     content.appendChild(category);
  283.                     
  284.                     // 组装项目
  285.                     li.appendChild(icon);
  286.                     li.appendChild(content);
  287.                     
  288.                     // 添加到列表
  289.                     itemList.appendChild(li);
  290.                 });
  291.             }
  292.             
  293.             // 更新统计信息
  294.             updateStats(filteredItems.length, items.length);
  295.         }
  296.         
  297.         // 更新统计信息
  298.         function updateStats(visibleCount, totalCount) {
  299.             stats.textContent = `显示 ${visibleCount} / ${totalCount} 个项目`;
  300.         }
  301.         
  302.         // 添加事件监听器
  303.         searchInput.addEventListener('input', renderItems);
  304.         
  305.         filterOptions.forEach(option => {
  306.             option.addEventListener('change', renderItems);
  307.         });
  308.         
  309.         // 初始渲染
  310.         renderItems();
  311.     </script>
  312. </body>
  313. </html>
复制代码

最佳实践和性能优化

避免频繁的DOM操作

频繁的DOM操作会导致性能问题,因为每次操作都可能引起浏览器的重排或重绘。
  1. <div id="container"></div>
  2. <button id="addItemsBtn">添加1000个项目</button>
  3. <script>
  4.     const container = document.getElementById('container');
  5.     const addItemsBtn = document.getElementById('addItemsBtn');
  6.    
  7.     addItemsBtn.addEventListener('click', function() {
  8.         // 不好的做法:频繁操作DOM
  9.         // for (let i = 0; i < 1000; i++) {
  10.         //     const item = document.createElement('div');
  11.         //     item.textContent = `项目 ${i + 1}`;
  12.         //     container.appendChild(item);
  13.         // }
  14.         
  15.         // 好的做法:使用文档片段减少DOM操作
  16.         const fragment = document.createDocumentFragment();
  17.         
  18.         for (let i = 0; i < 1000; i++) {
  19.             const item = document.createElement('div');
  20.             item.textContent = `项目 ${i + 1}`;
  21.             fragment.appendChild(item);
  22.         }
  23.         
  24.         container.appendChild(fragment);
  25.     });
  26. </script>
复制代码

使用事件委托

当有大量元素需要相同的事件处理时,使用事件委托可以减少内存使用和提高性能。
  1. <ul id="list">
  2.     <!-- 动态生成的列表项 -->
  3. </ul>
  4. <button id="addItemBtn">添加项目</button>
  5. <script>
  6.     const list = document.getElementById('list');
  7.     const addItemBtn = document.getElementById('addItemBtn');
  8.     let itemCount = 0;
  9.    
  10.     // 添加项目
  11.     addItemBtn.addEventListener('click', function() {
  12.         itemCount++;
  13.         const item = document.createElement('li');
  14.         item.textContent = `项目 ${itemCount}`;
  15.         item.className = 'list-item';
  16.         list.appendChild(item);
  17.     });
  18.    
  19.     // 不好的做法:为每个列表项单独添加事件监听器
  20.     // function addItemClickListeners() {
  21.     //     const items = document.querySelectorAll('.list-item');
  22.     //     items.forEach(item => {
  23.     //         item.addEventListener('click', function() {
  24.     //             console.log(`点击了: ${this.textContent}`);
  25.     //         });
  26.     //     });
  27.     // }
  28.    
  29.     // 好的做法:使用事件委托
  30.     list.addEventListener('click', function(event) {
  31.         // 检查点击的是否是列表项
  32.         if (event.target.tagName === 'LI') {
  33.             console.log(`点击了: ${event.target.textContent}`);
  34.         }
  35.     });
  36. </script>
复制代码

避免强制同步布局

强制同步布局(Layout Thrashing)是指JavaScript强制浏览器在执行过程中重新计算布局,这会导致性能问题。
  1. <div id="box" style="width: 100px; height: 100px; background-color: blue;"></div>
  2. <button id="animateBtn">动画</button>
  3. <script>
  4.     const box = document.getElementById('box');
  5.     const animateBtn = document.getElementById('animateBtn');
  6.    
  7.     animateBtn.addEventListener('click', function() {
  8.         // 不好的做法:强制同步布局
  9.         // for (let i = 0; i < 100; i++) {
  10.         //     box.style.width = (100 + i) + 'px';
  11.         //     // 读取宽度会导致强制同步布局
  12.         //     console.log(box.offsetWidth);
  13.         // }
  14.         
  15.         // 好的做法:批量读取和写入
  16.         let width = 100;
  17.         
  18.         // 先读取所有需要的值
  19.         const startWidth = box.offsetWidth;
  20.         
  21.         // 然后批量写入
  22.         for (let i = 0; i < 100; i++) {
  23.             width++;
  24.             box.style.width = width + 'px';
  25.         }
  26.         
  27.         // 最后读取最终值
  28.         console.log('最终宽度:', box.offsetWidth);
  29.     });
  30. </script>
复制代码

使用requestAnimationFrame进行动画

使用requestAnimationFrame而不是setTimeout或setInterval进行动画,可以获得更好的性能和更流畅的动画效果。
  1. <div id="animatedBox" style="width: 50px; height: 50px; background-color: red; position: absolute; top: 0; left: 0;"></div>
  2. <button id="startAnimationBtn">开始动画</button>
  3. <script>
  4.     const animatedBox = document.getElementById('animatedBox');
  5.     const startAnimationBtn = document.getElementById('startAnimationBtn');
  6.     let animationId = null;
  7.     let position = 0;
  8.    
  9.     startAnimationBtn.addEventListener('click', function() {
  10.         if (animationId) {
  11.             // 如果动画已经在运行,先停止
  12.             cancelAnimationFrame(animationId);
  13.             animationId = null;
  14.             startAnimationBtn.textContent = '开始动画';
  15.         } else {
  16.             // 开始动画
  17.             startAnimationBtn.textContent = '停止动画';
  18.             animate();
  19.         }
  20.     });
  21.    
  22.     function animate() {
  23.         // 更新位置
  24.         position += 2;
  25.         
  26.         // 如果超出边界,重置位置
  27.         if (position > window.innerWidth - 50) {
  28.             position = 0;
  29.         }
  30.         
  31.         // 更新元素位置
  32.         animatedBox.style.left = position + 'px';
  33.         
  34.         // 请求下一帧
  35.         animationId = requestAnimationFrame(animate);
  36.     }
  37. </script>
复制代码

使用虚拟滚动处理大量数据

当需要渲染大量数据时,使用虚拟滚动技术只渲染可见区域的项目,可以大大提高性能。
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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.             margin: 0;
  11.             padding: 20px;
  12.         }
  13.         
  14.         h1 {
  15.             text-align: center;
  16.         }
  17.         
  18.         .scroll-container {
  19.             height: 400px;
  20.             overflow-y: auto;
  21.             border: 1px solid #ddd;
  22.             position: relative;
  23.         }
  24.         
  25.         .scroll-content {
  26.             position: relative;
  27.         }
  28.         
  29.         .scroll-item {
  30.             padding: 15px;
  31.             border-bottom: 1px solid #eee;
  32.             box-sizing: border-box;
  33.             height: 50px;
  34.         }
  35.         
  36.         .scroll-item:nth-child(odd) {
  37.             background-color: #f9f9f9;
  38.         }
  39.         
  40.         .info {
  41.             margin-top: 10px;
  42.             text-align: center;
  43.             color: #666;
  44.         }
  45.     </style>
  46. </head>
  47. <body>
  48.     <h1>虚拟滚动示例</h1>
  49.    
  50.     <div id="scrollContainer" class="scroll-container">
  51.         <div id="scrollContent" class="scroll-content">
  52.             <!-- 虚拟滚动项将在这里动态生成 -->
  53.         </div>
  54.     </div>
  55.    
  56.     <div id="info" class="info">
  57.         显示 0 / 0 个项目
  58.     </div>
  59.     <script>
  60.         // 配置
  61.         const config = {
  62.             itemHeight: 50,       // 每个项目的高度
  63.             bufferSize: 5,        // 上下缓冲的项目数量
  64.             totalItems: 10000     // 总项目数
  65.         };
  66.         
  67.         // 获取DOM元素
  68.         const scrollContainer = document.getElementById('scrollContainer');
  69.         const scrollContent = document.getElementById('scrollContent');
  70.         const info = document.getElementById('info');
  71.         
  72.         // 状态
  73.         let scrollTop = 0;
  74.         let visibleStartIndex = 0;
  75.         let visibleEndIndex = 0;
  76.         
  77.         // 初始化
  78.         function init() {
  79.             // 设置滚动内容的高度
  80.             scrollContent.style.height = `${config.itemHeight * config.totalItems}px`;
  81.             
  82.             // 监听滚动事件
  83.             scrollContainer.addEventListener('scroll', handleScroll);
  84.             
  85.             // 初始渲染
  86.             renderVisibleItems();
  87.         }
  88.         
  89.         // 处理滚动事件
  90.         function handleScroll() {
  91.             scrollTop = scrollContainer.scrollTop;
  92.             
  93.             // 计算可见区域的起始和结束索引
  94.             visibleStartIndex = Math.floor(scrollTop / config.itemHeight);
  95.             visibleEndIndex = Math.min(
  96.                 visibleStartIndex + Math.ceil(scrollContainer.clientHeight / config.itemHeight),
  97.                 config.totalItems - 1
  98.             );
  99.             
  100.             // 添加缓冲区
  101.             const bufferedStartIndex = Math.max(0, visibleStartIndex - config.bufferSize);
  102.             const bufferedEndIndex = Math.min(config.totalItems - 1, visibleEndIndex + config.bufferSize);
  103.             
  104.             // 渲染可见项目
  105.             renderItems(bufferedStartIndex, bufferedEndIndex);
  106.             
  107.             // 更新信息
  108.             updateInfo();
  109.         }
  110.         
  111.         // 渲染指定范围的项目
  112.         function renderItems(startIndex, endIndex) {
  113.             // 清空当前内容
  114.             scrollContent.innerHTML = '';
  115.             
  116.             // 设置内容的位置
  117.             scrollContent.style.transform = `translateY(${startIndex * config.itemHeight}px)`;
  118.             
  119.             // 渲染项目
  120.             for (let i = startIndex; i <= endIndex; i++) {
  121.                 const item = createItem(i);
  122.                 scrollContent.appendChild(item);
  123.             }
  124.         }
  125.         
  126.         // 创建单个项目
  127.         function createItem(index) {
  128.             const item = document.createElement('div');
  129.             item.className = 'scroll-item';
  130.             item.textContent = `项目 ${index + 1}`;
  131.             return item;
  132.         }
  133.         
  134.         // 渲染可见项目(初始调用)
  135.         function renderVisibleItems() {
  136.             visibleEndIndex = Math.min(
  137.                 Math.ceil(scrollContainer.clientHeight / config.itemHeight),
  138.                 config.totalItems - 1
  139.             );
  140.             
  141.             renderItems(visibleStartIndex, visibleEndIndex);
  142.             updateInfo();
  143.         }
  144.         
  145.         // 更新信息
  146.         function updateInfo() {
  147.             const visibleCount = visibleEndIndex - visibleStartIndex + 1;
  148.             info.textContent = `显示 ${visibleCount} / ${config.totalItems} 个项目 (索引: ${visibleStartIndex}-${visibleEndIndex})`;
  149.         }
  150.         
  151.         // 初始化虚拟滚动
  152.         init();
  153.     </script>
  154. </body>
  155. </html>
复制代码

结论

JavaScript操作DOM是动态网页开发的核心技能。通过本教程,我们学习了如何选择DOM元素、修改元素内容和属性、处理用户事件以及创建动态交互效果。通过实际案例,我们掌握了待办事项列表、动态表单生成器和实时搜索过滤器的实现方法。同时,我们也了解了DOM操作的最佳实践和性能优化技巧,如避免频繁DOM操作、使用事件委托、避免强制同步布局、使用requestAnimationFrame进行动画以及虚拟滚动处理大量数据。

掌握这些技能后,你将能够创建更加动态、交互式和高性能的Web应用。记住,实践是掌握这些技能的关键,所以请尝试将这些技术应用到你的项目中,不断探索和学习新的DOM操作技巧。
回复

使用道具 举报

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

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.