构建简单的Todo List应用
开发
构建一个简单的Todo List应用程序
在这篇文章中,我们将学习如何构建一个简单的Todo List应用程序,该应用程序将允许用户添加和删除待办事项。我们将使用HTML、CSS和JavaScript来构建此应用程序。这将帮助我们掌握基本的Web开发技能。
功能需求
- 用户可以输入待办事项。
- 用户可以查看已添加的待办事项。
- 用户可以删除完成的待办事项。
方案概述
我们将分三步来实现这个Todo List应用程序:
- 步骤1:创建基本的HTML结构。
- 步骤2:添加样式以提高用户体验。
- 步骤3:使用JavaScript实现功能。
步骤1:创建基本的HTML结构
首先,我们需要创建一个简单的HTML文件来定义应用程序的结构。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo List</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Todo List</h1>
<div class="todo-container">
<input type="text" id="todo-input" placeholder="Add a new todo">
<button id="add-todo">Add</button>
<ul id="todo-list">
<!-- List items will appear here -->
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
步骤2:添加样式以提高用户体验
接下来,我们为应用程序添加一些CSS样式。创建一个文件 styles.css
并添加以下代码:
body {
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.todo-container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
text-align: center;
}
input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
width: 100%;
padding: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #218838;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
padding: 10px;
border: 1px solid #ddd;
margin-bottom: 5px;
border-radius: 4px;
}
li button {
background-color: #dc3545;
border-radius: 4px;
}
li button:hover {
background-color: #c82333;
}
步骤3:使用JavaScript实现功能
最后,我们编写JavaScript代码以使应用程序真正起作用。创建一个文件 script.js
并添加以下代码:
document.getElementById('add-todo').addEventListener('click', function() {
const todoInput = document.getElementById('todo-input');
const todoText = todoInput.value.trim();
if (todoText !== '') {
const todoList = document.getElementById('todo-list');
const li = document.createElement('li');
const textNode = document.createTextNode(todoText);
li.appendChild(textNode);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
li.appendChild(deleteButton);
todoList.appendChild(li);
// Clear the input field
todoInput.value = '';
// Add event listener for delete button
deleteButton.addEventListener('click', function() {
todoList.removeChild(li);
});
}
});
结论
通过完成以上步骤,我们已经创建了一个基本的Todo List应用程序。用户可以输入待办事项,看到他们的列表,还可以删除完成的任务。这是掌握客户端Web开发基本知识的良好起点。您可以尝试添加额外的功能,例如编辑功能或数据持久性,以扩展此项目。
编辑:一起学习网