构建简单的待办事项应用
开发
构建简单的待办事项(Todo)应用程序
在这篇文章中,我们将创建一个简单的待办事项(Todo)应用程序。通过这个项目,你将学习如何使用HTML、CSS和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 App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="app">
<h1>Todo List</h1>
<input type="text" id="taskInput" placeholder="Enter a new task">
<button id="addTaskButton">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
步骤 2:添加基本样式
接下来,在styles.css
中添加一些样式,使我们的应用看起来更好。
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
#app {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}
#taskInput {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 10px;
}
#addTaskButton {
width: 100%;
padding: 10px;
background-color: #5cb85c;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
#taskList {
list-style-type: none;
padding: 0;
}
.taskItem {
background: #e2e3ea;
margin: 5px 0;
padding: 10px;
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
}
.deleteButton {
background: #d9534f;
border: none;
color: white;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
步骤 3:实现功能逻辑
最后,在script.js
中编写JavaScript代码来实现添加和删除任务的功能。
document.getElementById('addTaskButton').addEventListener('click', function() {
const taskInput = document.getElementById('taskInput');
const taskValue = taskInput.value.trim();
if (taskValue) {
const taskList = document.getElementById('taskList');
const listItem = document.createElement('li');
listItem.className = 'taskItem';
const taskText = document.createElement('span');
taskText.textContent = taskValue;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'deleteButton';
deleteButton.addEventListener('click', function() {
taskList.removeChild(listItem);
});
listItem.appendChild(taskText);
listItem.appendChild(deleteButton);
taskList.appendChild(listItem);
taskInput.value = '';
}
});
解释
- HTML:创建输入框、按钮和任务列表的基础结构。
- CSS:为应用程序添加简单清晰的样式,使其更加美观。
- JavaScript:实现向列表中添加新任务和删除现有任务的逻辑。
这样,我们就构建了一个简单的待办事项应用程序。通过上述步骤,你可以体会到前端开发中的各个组成部分是如何协同工作的。此基础可以扩展为更复杂的功能,如持久化数据、添加任务优先级等。希望这篇文章对你有所帮助!
编辑:一起学习网