基于HTML和JavaScript的Todo应用:按回车键动态添加复选框与文本输入
待办清单页面解决方案
用textarea确实没法实现嵌入复选框这类交互元素的需求,得换成动态生成DOM元素的方式来做。下面是完整的实现代码,满足你的所有需求:
完整代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>待办清单</title> <style> #todo-container { height: 400px; width: 1200px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; font-size: 16px; } .todo-item { display: flex; align-items: center; margin-bottom: 8px; } .todo-item input[type="checkbox"] { margin-right: 8px; width: 18px; height: 18px; } .todo-input { flex: 1; border: none; outline: none; font-size: inherit; padding: 4px; } .todo-input:focus { background-color: #f5f5f5; } button { margin-top: 10px; padding: 8px 16px; cursor: pointer; } </style> </head> <body> <div id="todo-container"></div> <button name="Save" onclick="save()">Save</button> <script> const todoContainer = document.getElementById('todo-container'); // 初始化时添加第一个待办项 createTodoItem(); // 创建单个待办项的函数 function createTodoItem(text = '', checked = false) { const todoItem = document.createElement('div'); todoItem.className = 'todo-item'; // 创建复选框 const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = checked; // 勾选状态切换处理 checkbox.addEventListener('change', function() { input.style.textDecoration = this.checked ? 'line-through' : 'none'; }); // 创建文本输入框 const input = document.createElement('input'); input.type = 'text'; input.className = 'todo-input'; input.value = text; input.style.textDecoration = checked ? 'line-through' : 'none'; // 回车添加新待办项 input.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); createTodoItem(); todoContainer.lastElementChild.querySelector('.todo-input').focus(); } // 退格键处理:输入框为空时按退格,移除当前待办项并留空白行 else if (e.key === 'Backspace' && this.value === '') { e.preventDefault(); todoItem.remove(); // 容器为空时自动添加空白输入项 if (todoContainer.children.length === 0) { createTodoItem(); } } }); todoItem.appendChild(checkbox); todoItem.appendChild(input); todoContainer.appendChild(todoItem); } // 保存功能 function save() { const todos = []; document.querySelectorAll('.todo-item').forEach(item => { const checkbox = item.querySelector('input[type="checkbox"]'); const input = item.querySelector('.todo-input'); todos.push({ text: input.value, checked: checkbox.checked }); }); // 保存到localStorage,可按需改成发送到后端 localStorage.setItem('todolist', JSON.stringify(todos)); alert('待办清单已保存'); } // 页面加载时恢复保存的待办项 window.addEventListener('load', function() { const savedTodos = localStorage.getItem('todolist'); if (savedTodos) { const todos = JSON.parse(savedTodos); todoContainer.innerHTML = ''; todos.forEach(todo => { createTodoItem(todo.text, todo.checked); }); if (todos.length === 0) { createTodoItem(); } } }); </script> </body> </html>
关键功能说明
- 回车添加新项:每个输入框监听回车事件,触发后自动创建新的待办项并聚焦到新输入框。
- 复选框勾选效果:勾选后给对应文本添加删除线,样式可按需自定义。
- 退格键处理:输入框为空时按退格,会移除当前待办项;若所有项都被删除,自动生成空白输入项保证可继续操作。
- 保存与恢复:将待办项的文本和勾选状态存储到localStorage,页面刷新后自动恢复之前的内容。
内容的提问来源于stack exchange,提问作者Lavi
相关产品推荐
相关产品推荐

