编写html+css+js计算体重BMI的完整源代码
时间: 2023-06-01 15:06:37 浏览: 100
以下是一个计算BMI并呈现结果的完整 HTML、CSS 和 JavaScript 源代码.
HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>BMI计算器</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<h1>BMI计算器</h1>
<label for="height">身高(厘米):</label>
<input type="text" id="height">
<label for="weight">体重(千克):</label>
<input type="text" id="weight">
<button onclick="calculateBMI()">计算</button>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS:
```
.wrapper {
max-width: 500px;
margin: 0 auto;
text-align: center;
}
h1 {
font-size: 2rem;
margin-bottom: 2rem;
}
label {
display: block;
margin-top: 1rem;
font-size: 1.25rem;
}
input[type="text"] {
padding: 0.5rem;
border-radius: 5px;
border: none;
box-shadow: 0 0 10px rgba(0,0,0,0.3);
font-size: 1.25rem;
margin-top: 0.5rem;
}
button {
padding: 0.5rem 1rem;
border-radius: 5px;
border: none;
background-color: #007bff;
color: #fff;
font-size: 1.25rem;
margin-top: 1rem;
cursor: pointer;
}
#result {
margin-top: 2rem;
font-size: 1.5rem;
}
```
JavaScript:
```
function calculateBMI() {
var height = parseInt(document.getElementById("height").value);
var weight = parseInt(document.getElementById("weight").value);
if(isNaN(height) || isNaN(weight)) {
document.getElementById("result").innerHTML = "请输入数字";
return;
}
var bmi = weight / ((height / 100) * (height / 100));
bmi = bmi.toFixed(1);
var result = "";
if(bmi < 18.5) {
result = "您的BMI指数为 " + bmi + ",体重过轻。";
} else if(bmi >= 18.5 && bmi <= 24.9) {
result = "您的BMI指数为 " + bmi + ",体重正常。";
} else if(bmi >= 25 && bmi <= 29.9) {
result = "您的BMI指数为 " + bmi + ",体重过重。";
} else if(bmi >= 30) {
result = "您的BMI指数为 " + bmi + ",肥胖。";
}
document.getElementById("result").innerHTML = result;
}
```