上一篇
htmljs代码
- 行业动态
- 2025-05-03
- 3
HTML构建页面结构,JS添加交互逻辑,组合实现动态网页功能。(34字
代码结构说明
以下代码实现一个简单的动态任务列表功能,用户输入任务后点击按钮可将任务添加到列表中,并可删除任务。
模块 | 功能说明 |
---|---|
HTML | 构建基础页面结构(输入框、按钮、列表容器) |
CSS | 定义基本样式(布局、颜色、字体) |
JS | 实现任务添加、删除的交互逻辑 |
HTML 结构
<div class="container"> <h2>任务列表</h2> <input type="text" id="taskInput" placeholder="输入新任务"> <button id="addTaskBtn">添加任务</button> <ul id="taskList"></ul> </div>
CSS 样式
body { font-family: Arial, sans-serif; } .container { max-width: 400px; margin: 50px auto; } #taskInput { width: 70%; padding: 8px; } #addTaskBtn { padding: 8px 16px; } ul { list-style-type: none; padding: 0; margin-top: 20px; } li { background: #f4f4f4; margin-bottom: 10px; padding: 10px; border-radius: 4px; } .deleteBtn { float: right; color: red; cursor: pointer; }
JavaScript 逻辑
document.getElementById('addTaskBtn').addEventListener('click', function() { const taskInput = document.getElementById('taskInput'); const taskValue = taskInput.value.trim(); if (taskValue === '') { alert('任务内容不能为空!'); return; } // 创建新任务节点 const newTask = document.createElement('li'); newTask.innerHTML = `${taskValue} <span class="deleteBtn">删除</span>`; document.getElementById('taskList').appendChild(newTask); // 清空输入框 taskInput.value = ''; // 绑定删除事件 newTask.querySelector('.deleteBtn').addEventListener('click', function() { newTask.remove(); }); });
相关问题与解答
问题1:如何允许用户一次性添加多个任务?
解答:
修改输入框为多行输入(如<textarea>
),并通过换行符分割任务,更新JS逻辑如下:
document.getElementById('addTaskBtn').addEventListener('click', function() { const tasks = taskInput.value.split(' ').map(t => t.trim()).filter(t => t !== ''); tasks.forEach(task => { // 复用原有创建任务逻辑 }); });
问题2:如何给任务添加完成状态(例如划线效果)?
解答:
- 修改CSS增加
.completed
类:.completed { text-decoration: line-through; color: gray; }
- 在任务文本上绑定点击事件:
newTask.querySelector('span:first-child').addEventListener('click', function() { newTask.classList.toggle('completed'); });