一起学习网 一起学习网


构建简单待办事项应用

开发 To-Do List, HTML, CSS, JavaScript, web application 03-28

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

在本文中,我们将一步步创建一个简单的待办事项(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">
    <link rel="stylesheet" href="styles.css">
    <title>To-Do List App</title>
</head>
<body>
    <div class="container">
        <h1>To-Do List</h1>
        <input type="text" id="taskInput" placeholder="Add a new task...">
        <button id="addTaskBtn">Add Task</button>
        <ul id="taskList"></ul>
    </div>
    <script src="app.js"></script>
</body>
</html>

步骤二:设计应用程序的样式

接下来,我们将添加一些CSS来使我们的应用程序看起来更美观。

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

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

input, button {
    width: 100%;
    padding: 10px;
    margin-top: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
}

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

li {
    background-color: #f9f9f9;
    padding: 10px;
    border-bottom: 1px solid #ddd;
    position: relative;
}

li:hover {
    background-color: #f1f1f1;
}

li .deleteBtn {
    position: absolute;
    right: 10px;
    top: 10px;
    background-color: red;
    color: white;
    border: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    cursor: pointer;
}

步骤三:实现JavaScript功能

最后,我们将用JavaScript来实现应用程序的功能,包括添加和删除任务。

// app.js
document.getElementById('addTaskBtn').addEventListener('click', function() {
    const taskInput = document.getElementById('taskInput');
    const taskText = taskInput.value.trim();

    if (taskText !== "") {
        const taskList = document.getElementById('taskList');

        const taskItem = document.createElement('li');
        taskItem.textContent = taskText;

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = 'X';
        deleteBtn.className = 'deleteBtn';
        deleteBtn.onclick = function() {
            taskList.removeChild(taskItem);
        };

        taskItem.appendChild(deleteBtn);
        taskList.appendChild(taskItem);

        taskInput.value = "";
    }
});

结论

通过这些步骤,我们创建了一个简单但功能齐全的待办事项应用程序。尽管这个应用程序很基础,但它为理解事件处理和DOM操作提供了良好的实践。您可以进一步扩展这个应用程序,比如通过添加任务完成标记功能,或将任务持久化到本地存储中。希望这篇文章对您了解如何构建一个简单的web应用有所帮助。


编辑:一起学习网