就是这个样的粗爆,手搓一个计算器:BMI计算器
作为程序员,没有合适的工具,就得手搓一个,PC端,移动端均可适用。废话不多说,直接上代码。
HTML:
<div class="calculator">
<label for="height">身高 (cm):</label>
<input id="height" step="0.1" type="number" placeholder="请输入您的身高">
<label for="weight">体重 (kg):</label>
<input id="weight" step="0.1" type="number" placeholder="请输入您的体重">
<button onclick="calculateBMI()">计算</button>
<div class="result">
<p>计算结果:</p>
<p>BMI值: <span id="bmiValue">0</span></p>
<p>体重分类: <span id="bmiCategory">未知</span></p>
</div>
</div>
JS:
function calculateBMI() {const height = parseFloat(document.getElementById('height').value);const weight = parseFloat(document.getElementById('weight').value);if (isNaN(height) || isNaN(weight) || height <= 0 || weight <= 0) {alert('请输入有效的身高和体重');return;}const heightInMeters = height / 100; // 转换为米const bmi = weight / (heightInMeters * heightInMeters);document.getElementById('bmiValue').textContent = bmi.toFixed(2);let category = '';if (bmi < 18.5) {category = '偏瘦';} else if (bmi >= 18.5 && bmi < 24) {category = '正常';} else if (bmi >= 24 && bmi < 28) {category = '超重';} else {category = '肥胖';}document.getElementById('bmiCategory').textContent = category;
}
CSS:
.calculator {width: 300px;background-color: #333;color: white;padding: 20px;border-radius: 10px;box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}label {display: block;margin-bottom: 10px;font-size: 16px;
}input, select {width: 100%!important;padding: 10px!important;margin-bottom: 20px;color: #000000; border-radius: 5px;border: 1px solid #555;font-size: 16px!important;background-color: #ffffff!important;
}button {width: 100%;padding: 10px;background-color: #007bff;color: white;border: none;border-radius: 5px;cursor: pointer;font-size: 16px;
}button:hover {background-color: orange;
}.result {margin-top: 20px;text-align: center;
}option {background-color: #ffffff;
}p {font-size: 18px;margin-top: 5px!important;
}
线上运行,可以直接打开:BMI计算器