构建简单的Todo List应用
开发
构建一个简单的Todo List应用程序
在这篇文章中,我们将逐步构建一个简单的Todo List应用程序。这个项目将帮助初学者理解如何用HTML、CSS和JavaScript来创建交互式的Web应用程序。
第一步:设置基本的HTML结构
首先,我们创建一个简单的HTML文件来定义Todo List的基本结构。
<!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>
<div class="todo-container">
<h1>Todo List</h1>
<input type="text" id="todo-input" placeholder="Add a new todo">
<button id="add-todo-btn">Add</button>
<ul id="todo-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
在这段代码中,我们创建了一个输入框和一个按钮,用于添加新的待办事项。此外,我们创建了一个空的无序列表来显示待办事项。
第二步:添加基本的CSS样式
接下来,我们为Todo List应用添加一些基本的样式,以使其更具吸引力。
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.todo-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
margin-top: 0;
}
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-color: #f8f9fa;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 5px;
display: flex;
justify-content: space-between;
}
li button {
background-color: #dc3545;
border: none;
padding: 5px;
color: white;
border-radius: 4px;
cursor: pointer;
}
li button:hover {
background-color: #c82333;
}
这段CSS代码为我们的HTML元素添加了样式,使应用程序看起来更加整洁和现代。
第三步:编写JavaScript功能
最后,我们编写JavaScript代码来处理用户交互和应用程序逻辑。
// script.js
document.getElementById('add-todo-btn').addEventListener('click', function() {
const todoInput = document.getElementById('todo-input');
const todoText = todoInput.value.trim();
if (todoText !== '') {
const todoList = document.getElementById('todo-list');
const todoItem = document.createElement('li');
const todoItemText = document.createElement('span');
todoItemText.textContent = todoText;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', function() {
todoList.removeChild(todoItem);
});
todoItem.appendChild(todoItemText);
todoItem.appendChild(deleteButton);
todoList.appendChild(todoItem);
todoInput.value = '';
}
});
在这段JavaScript代码中,我们实现了一个简单的功能:当用户点击"Add"按钮时,会将输入框中的文本添加到Todo List中,并附带一个删除按钮,用户可以通过点击它来移除对应的待办事项。
结论
通过这篇教程,我们创建了一个简单的Todo List应用程序,使用了HTML、CSS和JavaScript。这个项目可以作为学习Web开发基础的起点。希望你在练习中享受编码的乐趣,并继续探索更多的Web开发技术!
编辑:一起学习网