基于html+css+js todolist完整代码
时间: 2024-12-22 08:12:04 浏览: 27
创建一个基于HTML、CSS和JavaScript的简单待办事项列表(TodoList)可以分为以下几个步骤。这里是一个基本示例:
1. **HTML结构**:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Todo List</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>待办事项列表</h1>
<input type="text" id="new-todo" placeholder="添加新任务...">
<button onclick="addTodo()">添加</button>
<ul id="todo-list"></ul>
<script src="scripts.js"></script>
</body>
</html>
```
2. **CSS样式** (styles.css):
```css
body {
font-family: Arial, sans-serif;
}
#todo-list {
list-style-type: none;
padding: 0;
}
li {
cursor: pointer;
margin-bottom: 5px;
}
.completed {
text-decoration: line-through;
}
```
3. **JavaScript功能** (scripts.js):
```javascript
const todoList = document.getElementById('todo-list');
function addTodo() {
const newTodo = document.getElementById('new-todo').value.trim();
if (newTodo) {
const li = document.createElement('li');
li.textContent = newTodo;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.addEventListener('change', toggleCompletion);
li.appendChild(checkbox);
li.appendChild(document.createTextNode(newTodo));
todoList.appendChild(li);
document.getElementById('new-todo').value = '';
}
}
function toggleCompletion(event) {
event.target.parentElement.classList.toggle('completed');
}
// 示例:预设一些默认项
window.onload = function() {
todoList.innerHTML += `
<li class="completed">完成任务1</li>
<li>任务2</li>
<li class="completed">已完成的任务3</li>
`;
};
```
阅读全文