构建简单Todo应用程序
开发
构建一个简单的Todo应用程序:从零开始
在本文中,我们将开发一个简单的Todo应用程序,帮助你掌握前端开发的基础知识。我们将使用HTML、CSS和JavaScript构建这一应用。
第一步:设置基础HTML结构
首先,创建一个新的HTML文件,命名为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 List</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="app">
<h1>My Todo List</h1>
<input type="text" id="todo-input" placeholder="Add a new todo">
<button id="add-btn">Add</button>
<ul id="todo-list"></ul>
</div>
<script src="app.js"></script>
</body>
</html>
第二步:设计简洁的CSS样式
接下来,我们将创建一个CSS文件来美化我们的应用。新建一个名为styles.css
的文件,并添加以下样式:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#app {
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 3px;
}
button {
width: 100%;
padding: 10px;
background: #5cb85c;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
button:hover {
background: #4cae4c;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background: #eee;
margin: 5px 0;
padding: 10px;
border-radius: 3px;
display: flex;
justify-content: space-between;
align-items: center;
}
li .delete-btn {
background: #d9534f;
color: white;
border: none;
padding: 5px;
border-radius: 3px;
cursor: pointer;
}
li .delete-btn:hover {
background: #c9302c;
}
第三步:实现JavaScript逻辑
在这一步,我们会编写JavaScript来让我们的应用程序具有交互性。在你的项目目录中,创建一个名为app.js
的文件,并添加以下代码:
document.getElementById('add-btn').addEventListener('click', function() {
const todoInput = document.getElementById('todo-input');
const todoText = todoInput.value.trim();
if (todoText !== '') {
addTodo(todoText);
todoInput.value = '';
}
});
function addTodo(text) {
const todoList = document.getElementById('todo-list');
const todoItem = document.createElement('li');
todoItem.textContent = text;
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.classList.add('delete-btn');
deleteBtn.addEventListener('click', function() {
todoList.removeChild(todoItem);
});
todoItem.appendChild(deleteBtn);
todoList.appendChild(todoItem);
}
最后的总结
现在你已经成功地创建了一个简单的Todo应用程序。通过这个过程,我们学习了如何结合HTML、CSS和JavaScript来构建一个具有实际用途的小工具。代码很简洁,但它涵盖了很多基本的前端开发概念,包括元素操作、事件处理和样式应用。
你可以继续扩展这个Todo应用,增加如编辑功能、本地存储持久化数据等功能,这是一个很好的实践项目基础。
编辑:一起学习网