使用JavaScript设计一个BMI计算器
身体质量指数(BMI)计算器可以根据身高和体重计算BMI值。对于大多数人来说,BMI是一个相对可靠的体脂肪指标。
公式:
BMI = (weight) / (height * height)
height in cms
这是我们即将制作的BMI计算器的预览。
方法: BMI是从个体的体重和身高计算出的一个数字。为了得出BMI,我们将从用户那里获取输入(身高和体重),并将其存储在height和weight变量中以进行进一步的计算。计算过程很简单,我们只需将体重(以千克为单位)除以身高的平方。现在根据计算出的BMI,它将执行相应的if-else语句。我们还检查用户是否在未输入任何内容的情况下按下提交按钮,在这种情况下,我们将打印提供身高或提供体重。
使用HTML,我们提供所需的结构、输入选项和提交按钮。借助CSS,我们通过提供颜色和所需的字体等来美化我们的结构。
在JavaScript部分,我们将处理获取的输入,并在计算后打印出相应的输出。
示例: 在此示例中,我们将在index.html文件中构建结构,并在app.js文件中实现逻辑。
HTML代码
<!-- index.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BMI Calculator</title>
</head>
<body style="background-color: rgb(244, 255, 244)">
<div class="container">
<h1>BMI Calculator</h1>
<!-- Option for providing height
and weight to the user-->
<p>Height (in cm)</p>
<input type="text" id="height" />
<p>Weight (in kg)</p>
<input type="text" id="weight" />
<button id="btn">Calculate</button>
<div id="result"></div>
</div>
</body>
</html>
JavaScript 代码
window.onload = () => {
let button = document.querySelector("#btn");
// Function for calculating BMI
button.addEventListener("click", calculateBMI);
};
function calculateBMI() {
/* Getting input from user into height variable.
Input is string so typecasting is necessary. */
let height = parseInt(document
.querySelector("#height").value);
/* Getting input from user into weight variable.
Input is string so typecasting is necessary.*/
let weight = parseInt(document
.querySelector("#weight").value);
let result = document.querySelector("#result");
// Checking the user providing a proper
// value or not
if (height === "" || isNaN(height))
result.innerHTML = "Provide a valid Height!";
else if (weight === "" || isNaN(weight))
result.innerHTML = "Provide a valid Weight!";
// If both input is valid, calculate the bmi
else {
// Fixing upto 2 decimal places
let bmi = (weight / ((height * height)
/ 10000)).toFixed(2);
// Dividing as per the bmi conditions
if (bmi < 18.6) result.innerHTML =
`Under Weight : <span>{bmi}</span>`;
else if (bmi >= 18.6 && bmi<24.9)
result.innerHTML =
`Normal : <span>{bmi}</span>`;
else result.innerHTML =
`Over Weight : <span>${bmi}</span>`;
}
}
输出: