一起学习网 一起学习网


构建简单的待办事项应用程序

开发 To-Do List, Web开发, HTML, CSS, JavaScript 06-05

构建一个简单的待办事项应用程序

在这篇文章中,我们将通过构建一个简单的待办事项(To-Do List)应用程序来学习基本的Web开发技术。我们将使用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 id="app">
        <h1>待办事项列表</h1>
        <input type="text" id="taskInput" placeholder="添加新的任务">
        <button id="addTaskButton">添加任务</button>
        <ul id="taskList"></ul>
    </div>
    <script src="app.js"></script>
</body>
</html>

第二步:设计CSS样式

接下来,我们将使用CSS来美化我们的应用程序,使其更具吸引力。

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

#app {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}

h1 {
    font-size: 24px;
    margin-bottom: 20px;
}

input, button {
    padding: 10px;
    margin-bottom: 10px;
    width: calc(100% - 22px);
    box-sizing: border-box;
}

button {
    background-color: #007BFF;
    color: #fff;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}

ul {
    list-style: none;
    padding: 0;
}

li {
    padding: 10px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

li:last-child {
    border-bottom: none;
}

li button {
    background-color: #DC3545;
    margin-left: 10px;
    width: auto;
}

第三步:实现JavaScript交互功能

最后,我们将编写JavaScript代码,使我们的待办事项应用程序具有交互性。我们将实现添加和删除任务的功能。

document.addEventListener('DOMContentLoaded', () => {
    const taskInput = document.getElementById('taskInput');
    const addTaskButton = document.getElementById('addTaskButton');
    const taskList = document.getElementById('taskList');

    addTaskButton.addEventListener('click', () => {
        const taskText = taskInput.value.trim();
        if (taskText !== '') {
            const li = document.createElement('li');
            li.textContent = taskText;

            const deleteButton = document.createElement('button');
            deleteButton.textContent = '删除';
            deleteButton.addEventListener('click', () => {
                taskList.removeChild(li);
            });

            li.appendChild(deleteButton);
            taskList.appendChild(li);
            taskInput.value = '';
        }
    });
});

结束语

到这里,我们已经成功创建了一个简单的待办事项应用程序。这个项目演示了如何使用HTML定义结构,CSS进行样式美化,以及JavaScript实现交互功能。通过这样的练习,你可以更好地理解Web开发的基础知识,并为以后更复杂的项目打下基础。继续探索和练习,你会发现更多有趣的Web开发技巧和模式。


编辑:一起学习网