需求:
有92号汽油和95号可以选择,选择你需要的汽油,并输入需要加油的升数,点击按钮"计算总价钱
"在div中可以得到你所需要支付的价格。结构如下图所示:
详细代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 500px;
height: 100px;
background-color: pink;
border: 5px solid skyblue;
border-radius: 10px;
}
div {
margin-top: 20px;
}
</style>
</head>
<body>
<div>
<label for="radio1">92号,8.56元/升</label>
<input type="radio" name="oil" checked id="radio1" value="8.56">
</div>
<div>
<label for="radio">95号,9.16元/升</label>
<input type="radio" name="oil" id="radio2" value="9.16">
</div>
<div>
<input type="text" placeholder="请输入加油的升数" name="oil" id="txt">
</div>
<div>
<button id="btn">计算总价钱</button>
</div>
<div id="box"></div>
</body>
<script>
// 获取页面元素
var radio1 = document.getElementById("radio1");
var radio2 = document.getElementById("radio2");
var txt = document.getElementById("txt");
var btn = document.getElementById("btn");
var box = document.getElementById("box");
// 按钮的点击事件
btn.onclick = function () {
// 获取文本框的值
var num = Number(txt.value);
// console.log(num)
// 判断选中哪个radio
if (radio1.checked) {
var price = Number(radio1.value);
}
else {
var price = Number(radio2.value);
}
var total = (num * price).toFixed(2);
box.innerHTML = "您需要支付:" + total + "元!" ;
}
</script>
</html>
效果: