
1. 应用概述与核心功能
在多人共同消费场景中,费用分摊是一个常见需求。本教程将引导您开发一个基于web的简易应用,旨在实现以下核心功能:
- 记录个体消费: 用户可以输入参与者的姓名(文本类型输入)及其对应的消费金额(数字类型输入)。
- 动态数据管理: 应用内部使用JavaScript数组来存储所有消费记录。该数组能够支持新增记录,并能在用户输入同名参与者时更新其消费金额,而非重复添加。
- 实时计算与展示: 自动汇总所有已记录的消费金额,统计当前参与的总人数,并即时计算出每人平均应分摊的金额。
- 用户界面更新: 所有记录明细、总金额、参与人数以及人均分摊金额都将实时动态地显示在网页上,提供直观的用户反馈。
2. HTML结构:构建用户界面
首先,我们需要搭建应用的HTML骨架,定义输入控件、操作按钮以及用于显示结果的区域。以下是完整的HTML代码,其中包含了一些基础的CSS样式以提升可读性。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>费用分摊应用</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
h1 { color: #2c3e50; text-align: center; margin-bottom: 30px; }
p { margin-bottom: 5px; }
input[type="text"], input[type="number"] {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box; /* 包含padding和border在内的宽度 */
}
button {
padding: 12px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
display: block;
width: 100%;
max-width: 200px;
margin: 0 auto 20px auto;
}
button:hover { background-color: #45a049; }
.result-section {
background-color: #e8f5e9;
border: 1px solid #c8e6c9;
padding: 15px;
margin-top: 25px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.result-section p { margin: 8px 0; font-size: 1.1em; }
.result-section p span { font-weight: bold; color: #388e3c; }
#list {
background-color: #ffffff;
border: 1px solid #ddd;
padding: 15px;
margin-top: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
#list h3 { color: #2c3e50; margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 15px; }
#list p { margin: 8px 0; padding-left: 10px; border-left: 3px solid #66bb6a; }
</style>
</head>
<body>
<h1>费用分摊应用</h1>
<p>请输入每位参与者的姓名和消费金额:</p>
<p>姓名</p>
<input type="text" id="nombre" placeholder="例如:张三">
<br>
<p>金额</p>
<input type="number" id="monto" placeholder="例如:100">
<br>
<button onclick="ir()">添加/更新记录</button>
<br>
<div class="result-section">
<p>总支出: <span id="final">0</span> 元</p>
<p>参与人数: <span id="aporte">0</span> 人</p>
<p id="average">人均分摊: 0 元</p>
</div>
<div id="list">
<h3>消费明细:</h3>
<!-- 消费记录将在此处动态显示 -->
</div>
<script src="script.js"></script>
</body>
</html>HTML元素说明:
- <h1> 和 <p>:提供应用标题和功能说明。
- <input type="text" id="nombre">:用于输入参与者的姓名。
- `










