首先,我们需要一些HTML来构建基本的页面结构,接着是一些CSS来美化页面,最后是JavaScript来实现功能。
HTML (index.html)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>待办事项列表</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container"><h1>我的待办事项</h1><input type="text" id="new-todo" placeholder="输入新事项..."><button onclick="addTodo()">添加</button><ul id="todo-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (styles.css)
body {font-family: Arial, sans-serif;
}.container {width: 300px;margin: 50px auto;
}#new-todo {width: calc(100% - 22px);padding: 10px;box-sizing: border-box;
}button {width: 100%;padding: 10px;background-color: #5cb85c;color: white;border: none;cursor: pointer;
}button:hover {background-color: #4cae4c;
}ul {list-style: none;padding: 0;
}li {padding: 10px;border-bottom: 1px solid #ddd;display: flex;justify-content: space-between;
}li.completed {text-decoration: line-through;color: #aaa;
}
JavaScript (script.js)
javascript">function addTodo() {const input = document.getElementById('new-todo');const todoText = input.value.trim();if (todoText !== '') {const li = document.createElement('li');li.textContent = todoText;const deleteButton = document.createElement('button');deleteButton.textContent = '完成';deleteButton.onclick = function() {li.remove();};li.appendChild(deleteButton);li.onclick = function() {li.classList.toggle('completed');};document.getElementById('todo-list').appendChild(li);input.value = ''; // 清空输入框}
}
这段代码创建了一个简单的待办事项列表。用户可以在文本框中输入新的待办事项,点击“添加”按钮后,该事项会被加入到列表中。当点击列表中的某一项时,该项会被标记为已完成(通过给<li>
元素添加completed
类)。如果点击了“完成”按钮,则该项会被从列表中移除。