118 lines
2.1 KiB
HTML
118 lines
2.1 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="zh-CN">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>金额输入 Demo</title>
|
|
|
|
<style>
|
|
body {
|
|
margin: 0;
|
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI";
|
|
background: #f5f6f7;
|
|
}
|
|
|
|
.container {
|
|
max-width: 420px;
|
|
margin: 0 auto;
|
|
background: #fff;
|
|
min-height: 100vh;
|
|
padding: 20px;
|
|
}
|
|
|
|
.amount-wrapper {
|
|
text-align: center;
|
|
padding: 30px 0;
|
|
cursor: pointer;
|
|
}
|
|
|
|
.amount-label {
|
|
font-size: 14px;
|
|
color: #999;
|
|
margin-bottom: 6px;
|
|
}
|
|
|
|
.amount {
|
|
font-size: 42px;
|
|
font-weight: 600;
|
|
color: #111;
|
|
letter-spacing: -1px;
|
|
}
|
|
|
|
/* 点击反馈 */
|
|
.amount-wrapper:active {
|
|
opacity: 0.6;
|
|
}
|
|
|
|
/* 隐藏输入 */
|
|
.hidden-input {
|
|
position: absolute;
|
|
opacity: 0;
|
|
pointer-events: none;
|
|
}
|
|
</style>
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<div class="container">
|
|
|
|
<!-- 金额 -->
|
|
<div class="amount-wrapper" onclick="focusInput()">
|
|
<div class="amount-label">金额</div>
|
|
<div class="amount" id="amount">¥ 0.00</div>
|
|
</div>
|
|
|
|
<!-- 隐藏输入 -->
|
|
<input
|
|
id="input"
|
|
class="hidden-input"
|
|
type="text"
|
|
inputmode="decimal"
|
|
oninput="handleInput(this.value)"
|
|
/>
|
|
|
|
</div>
|
|
|
|
<script>
|
|
let value = "0";
|
|
|
|
function focusInput() {
|
|
document.getElementById("input").focus();
|
|
}
|
|
|
|
function handleInput(text) {
|
|
// 只保留数字和小数点
|
|
let v = text.replace(/[^\d.]/g, "");
|
|
|
|
// 只允许一个 .
|
|
const parts = v.split(".");
|
|
if (parts.length > 2) {
|
|
v = parts[0] + "." + parts[1];
|
|
}
|
|
|
|
// 限制两位小数
|
|
if (v.includes(".")) {
|
|
let [int, dec] = v.split(".");
|
|
v = int + "." + dec.slice(0, 2);
|
|
}
|
|
|
|
// 去前导0
|
|
if (v.startsWith("0") && v[1] !== ".") {
|
|
v = v.replace(/^0+/, "");
|
|
}
|
|
|
|
if (v === "") v = "0";
|
|
|
|
value = v;
|
|
updateUI();
|
|
}
|
|
|
|
function updateUI() {
|
|
document.getElementById("amount").innerText = "¥ " + value;
|
|
document.getElementById("input").value = value;
|
|
}
|
|
</script>
|
|
|
|
</body>
|
|
</html> |