创建简单Todo应用程序
开发
实现一个简单的Todo应用程序
在这篇文章中,我们将创建一个简单的Todo应用程序,使用HTML、CSS和JavaScript。这款应用程序将允许用户添加、删除和标记任务为已完成。我们将通过逐步指导来实现这一功能。
第一步:设置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 class="todo-container">
<h1>Todo List</h1>
<input type="text" id="task-input" placeholder="Enter new task">
<button id="add-task-btn">Add Task</button>
<ul id="task-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
第二步:添加CSS样式
接下来,我们为Todo应用程序添加一些基本的样式,使其更易于使用和美观。
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f7f7f7;
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;
}
#task-input {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
#add-task-btn {
width: 100%;
padding: 10px;
background-color: #28a745;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
#add-task-btn:hover {
background-color: #218838;
}
#task-list {
list-style-type: none;
padding: 0;
}
.task-item {
display: flex;
justify-content: space-between;
padding: 8px;
background-color: #f9f9f9;
border-bottom: 1px solid #ddd;
}
.task-item.completed {
text-decoration: line-through;
color: #6c757d;
}
.delete-btn {
background-color: #dc3545;
color: #fff;
border: none;
border-radius: 4px;
padding: 5px;
cursor: pointer;
}
第三步:编写JavaScript功能
最后,我们编写JavaScript代码来实现添加、删除和标记任务为已完成的功能。
document.addEventListener('DOMContentLoaded', () => {
const taskInput = document.getElementById('task-input');
const addTaskBtn = document.getElementById('add-task-btn');
const taskList = document.getElementById('task-list');
addTaskBtn.addEventListener('click', () => {
const taskText = taskInput.value.trim();
if (taskText !== '') {
const taskItem = document.createElement('li');
taskItem.className = 'task-item';
taskItem.innerHTML = `
<span>${taskText}</span>
<button class="delete-btn">Delete</button>
`;
taskList.appendChild(taskItem);
taskInput.value = '';
const deleteBtn = taskItem.querySelector('.delete-btn');
deleteBtn.addEventListener('click', () => {
taskList.removeChild(taskItem);
});
taskItem.addEventListener('click', () => {
taskItem.classList.toggle('completed');
});
}
});
});
总结
这篇文章展示了如何使用HTML、CSS和JavaScript创建一个简单的Todo应用程序。通过使用事件监听器,我们实现了添加新任务、删除任务以及标记任务为已完成的功能。这个项目不仅是一个很好的练习项目,还可以作为更复杂应用程序的基础。希望这篇文章对你学习开发有所帮助!
编辑:一起学习网