要实现输入数量和价格自动计算输出金额的功能,可以使用JavaScript来监听输入框的变化,并实时计算金额。以下是一个简单的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自动计算金额</title>
</head>
<body>
<label for="quantity">数量:</label>
<input type="number" id="quantity" step="1" value="0">
<label for="price">单价:</label>
<input type="number" id="price" step="0.01" value="0">
<label for="total">总金额:</label>
<input type="number" id="total" step="0.01" value="0" readonly>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const quantityInput = document.getElementById('quantity');
const priceInput = document.getElementById('price');
const totalInput = document.getElementById('total');
function calculateTotal() {
const quantity = parseFloat(quantityInput.value);
const price = parseFloat(priceInput.value);
const total = (quantity * price).toFixed(2);
totalInput.value = total;
}
quantityInput.addEventListener('input', calculateTotal);
priceInput.addEventListener('input', calculateTotal);
});
readonly
),因为它是由其他两个输入框计算得出的。DOMContentLoaded
事件确保DOM完全加载后再执行脚本。calculateTotal
函数,该函数读取数量和单价的值,计算总金额,并将结果显示在总金额输入框中。input
事件监听器,以便在用户输入时实时调用calculateTotal
函数。parseFloat
函数将输入转换为浮点数,非数字字符会被转换为NaN
,可以在计算前进行检查和处理。parseFloat
函数将输入转换为浮点数,非数字字符会被转换为NaN
,可以在计算前进行检查和处理。通过以上代码和处理方法,可以有效实现输入数量和价格自动计算输出金额的功能,并确保其稳定性和准确性。
领取专属 10元无门槛券
手把手带您无忧上云