创建简单Todo应用程序
开发
创建一个简单的Todo应用程序:从设计到实现
在这篇文章中,我们将创建一个简单的Todo应用程序。这个应用程序将允许用户添加、查看和删除待办事项。我们将使用HTML、CSS和JavaScript来实现这个功能。
第一步:设置HTML结构
首先,我们需要创建一个基本的HTML结构来容纳我们的Todo应用程序。
File: /home/user/project/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="app">
<h1>Todo List</h1>
<input type="text" id="todo-input" placeholder="Add a new todo">
<button id="add-todo">Add</button>
<ul id="todo-list"></ul>
</div>
<script src="app.js"></script>
</body>
</html>
第二步:设计CSS样式
接下来,我们将为我们的应用程序添加一些基本的样式,以使其更具吸引力。
File: /home/user/project/styles.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#app {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
margin: 0 0 20px;
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;
}
button:hover {
background-color: #218838;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
background: #f9f9f9;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}
li:last-child {
border-bottom: none;
}
li button {
background-color: #dc3545;
margin-left: 10px;
}
li button:hover {
background-color: #c82333;
}
第三步:实现JavaScript功能
最后,我们将使用JavaScript来实现添加和删除待办事项的功能。
File: /home/user/project/app.js
document.addEventListener('DOMContentLoaded', () => {
const todoInput = document.getElementById('todo-input');
const addTodoButton = document.getElementById('add-todo');
const todoList = document.getElementById('todo-list');
addTodoButton.addEventListener('click', () => {
const todoText = todoInput.value.trim();
if (todoText !== '') {
addTodoItem(todoText);
todoInput.value = '';
}
});
function addTodoItem(text) {
const li = document.createElement('li');
li.textContent = text;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', () => {
todoList.removeChild(li);
});
li.appendChild(deleteButton);
todoList.appendChild(li);
}
});
总结
通过这三个简单的步骤,我们创建了一个基本的Todo应用程序。用户可以通过输入框添加新的待办事项,并通过点击“Delete”按钮删除它们。这个项目展示了如何结合使用HTML、CSS和JavaScript来创建一个简单的Web应用程序。你可以根据需要扩展这个应用程序,比如添加持久化存储功能或更复杂的样式。
编辑:一起学习网