构建简单待办事项应用
开发
构建一个简单的待办事项应用程序
在这篇文章中,我们将创建一个简单的待办事项(To-Do List)应用程序。这个应用程序将允许用户添加、查看和删除待办事项。我们将使用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>待办事项应用</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="app-container">
<h1>待办事项列表</h1>
<input type="text" id="todo-input" placeholder="输入待办事项">
<button id="add-btn">添加</button>
<ul id="todo-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
第二步:设计样式
接下来,我们为应用程序添加一些基本的CSS样式。
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.app-container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
text-align: center;
color: #333;
}
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 {
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 5px;
display: flex;
justify-content: space-between;
align-items: center;
}
li button {
background-color: #d9534f;
border: none;
padding: 5px 10px;
color: white;
border-radius: 4px;
cursor: pointer;
}
li button:hover {
background-color: #c9302c;
}
第三步:实现JavaScript功能
最后,我们将添加JavaScript来实现添加、查看和删除待办事项的功能。
document.getElementById('add-btn').addEventListener('click', function() {
const todoInput = document.getElementById('todo-input');
const todoText = todoInput.value.trim();
if (todoText !== '') {
const todoList = document.getElementById('todo-list');
const li = document.createElement('li');
li.textContent = todoText;
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '删除';
deleteBtn.addEventListener('click', function() {
todoList.removeChild(li);
});
li.appendChild(deleteBtn);
todoList.appendChild(li);
todoInput.value = '';
}
});
结论
通过这三个简单的步骤,我们创建了一个基本的待办事项应用程序。这个应用程序演示了如何使用HTML来构建结构,CSS来美化样式,以及JavaScript来实现功能。你可以根据需要进一步扩展和改进这个应用,比如添加持久化存储、编辑功能等。
编辑:一起学习网