一个简单的JavaScript网页设计案例,它将展示一个交互式的待办事项列表。用户可以添加新的待办事项,并且能够通过点击来标记为已完成或删除它们。
HTML (index.html)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>待办事项列表</title>
<style>
body {
font-family: Arial, sans-serif;
}
.todo-app {
max-width: 500px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.todo-input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 3px;
}
.todo-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #eee;
}
.todo-item.completed {
text-decoration: line-through;
color: #aaa;
}
.btn-delete {
background: none;
border: none;
cursor: pointer;
color: red;
}
</style>
</head>
<body>
<div class="todo-app">
<h2>我的待办事项</h2>
<input type="text" id="new-todo" class="todo-input" placeholder="添加新任务...">
<ul id="todo-list"></ul>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
document.addEventListener('DOMContentLoaded', function() {
const todoInput = document.getElementById('new-todo');
const todoList = document.getElementById('todo-list');
// 添加新待办事项
todoInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter' && todoInput.value.trim()) {
addTodoItem(todoInput.value);
todoInput.value = ''; // 清空输入框
}
});
// 添加待办事项到列表
function addTodoItem(text) {
const item = document.createElement('li');
item.className = 'todo-item';
item.textContent = text;
const deleteButton = document.createElement('button');
deleteButton.className = 'btn-delete';
deleteButton.textContent = '×';
deleteButton.addEventListener('click', function() {
todoList.removeChild(item);
});
item.appendChild(deleteButton);
item.addEventListener('click', function() {
item.classList.toggle('completed');
});
todoList.appendChild(item);
}
});
这个例子中包括了HTML、CSS和JavaScript代码。HTML部分定义了页面结构,CSS用于样式设置,而JavaScript则处理逻辑,如添加待办事项、删除待办事项以及切换完成状态等。