创建简单的Todo应用程序
开发
如何创建一个简单的Todo应用程序
在这篇文章中,我们将创建一个简单的Todo应用程序。这个应用程序将允许用户添加、查看和删除待办事项。我们将使用HTML、CSS和JavaScript来实现这个功能。
第一步:创建HTML结构
首先,我们需要创建一个基本的HTML文件来构建应用程序的结构。
File: /home/user/project/todo.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 {
font-size: 24px;
margin-bottom: 20px;
}
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: #5cb85c;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #4cae4c;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background: #f9f9f9;
margin-bottom: 5px;
padding: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
li button {
background-color: #d9534f;
padding: 5px 10px;
border-radius: 4px;
}
li button:hover {
background-color: #c9302c;
}
第三步:编写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的基础项目,后续可以根据需要进行功能扩展。
编辑:一起学习网