设计一个简单的计算BMI的Web小程序示例,使用avaScript 和 HTML 实现。代码中将根据输入华氏温度转 摄氏度或输入摄氏底转华氏度,并显示结果。
时间: 2024-03-10 16:47:23 浏览: 12
好的,以下是使用 HTML 和 JavaScript 实现的计算 BMI 的 Web 小程序示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>BMI计算器</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: Arial, sans-serif;
font-size: 16px;
background-color: #f5f5f5;
color: #333;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 auto;
max-width: 400px;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
label {
display: block;
margin-bottom: 10px;
font-weight: bold;
}
input[type="text"] {
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
margin-bottom: 20px;
width: 100%;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px;
border-radius: 5px;
border: none;
cursor: pointer;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
.result {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>BMI计算器</h1>
<form>
<label>请输入身高(单位:米):</label>
<input type="text" id="height" placeholder="请输入身高">
<label>请输入体重(单位:千克):</label>
<input type="text" id="weight" placeholder="请输入体重">
<input type="submit" value="计算" onclick="calculateBMI()">
<div class="result" id="result"></div>
</form>
<script>
function calculateBMI() {
var heightInput = document.getElementById("height").value;
var weightInput = document.getElementById("weight").value;
var heightValue = parseFloat(heightInput);
var weightValue = parseFloat(weightInput);
var resultElement = document.getElementById("result");
if (isNaN(heightValue) || isNaN(weightValue)) {
alert("请输入有效的身高和体重");
} else if (heightValue <= 0 || weightValue <= 0) {
alert("身高和体重必须大于零");
} else {
var bmiValue = weightValue / (heightValue * heightValue);
var bmiCategory;
if (bmiValue < 18.5) {
bmiCategory = "偏瘦";
} else if (bmiValue >= 18.5 && bmiValue < 24.9) {
bmiCategory = "正常";
} else if (bmiValue >= 24.9 && bmiValue < 29.9) {
bmiCategory = "偏胖";
} else {
bmiCategory = "肥胖";
}
resultElement.innerHTML = "你的BMI指数为:" + bmiValue.toFixed(2) + ",属于" + bmiCategory + "范畴。";
}
}
</script>
</body>
</html>
```
这个程序可以计算 BMI 指数并显示结果,根据计算结果判断体重是否偏瘦、正常、偏胖或肥胖。在页面中输入身高和体重后,点击“计算”按钮即可计算出 BMI 指数并在页面中显示结果。注意,程序中的一些细节可能需要根据实际情况进行修改。