我正在创建一个 BMI 指数计算器,到目前为止一切都很好,当我考虑如何根据他们的 BMI 结果将 div 类的背景颜色更改为特定颜色时,我迷路了。
例如:
- 如果此人
体重不足
,则应为:灰色
- 如果这个人
正常
,它应该是:blue
- 如果此人
超重
,则应该是:橙色
- 如果这个人
肥胖
,它应该是:红色
我该怎么做,请帮忙...
这是 HTML CSS 和 Javascript
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
function computeBMI() {
//Obtain user inputs
var height = Number(document.getElementById("height").value);
var heightunits = document.getElementById("heightunits").value;
var weight = Number(document.getElementById("weight").value);
var weightunits = document.getElementById("weightunits").value;
if (heightunits == "inches") height /= 39.3700787;
if (weightunits == "lb") weight /= 2.20462;
var BMI = weight / Math.pow(height, 2);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var result;
if (BMI <= 18.5) {
result = 'underweight';
} else if (BMI <= 24.9) {
result = 'Normal';
} else if (BMI <= 29.9) {
result = 'Overweight';
} else {
result='Obese';
}
}
</script>
<style type="text/css">
.resultclass{ background-color:yellow; width:500px; height:300px;}
.underweight{ background-color:grey; width:500px; height:300px;}
.normal{ background-color:blue; width:500px; height:300px;}
.overweight{ background-color:orange; width:500px; height:300px;}
.obese{ background-color:red; width:500px; height:300px;}
</style>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
<p>Enter your height: <input type="text" id="height"/>
<select type="multiple" id="heightunits">
<option value="metres" selected="selected">metres</option>
<option value="inches">inches</option>
</select>
</p>
<p>Enter your weight: <input type="text" id="weight"/>
<select type="multiple" id="weightunits">
<option value="kg" selected="selected">kilograms</option>
<option value="lb">pounds</option>
</select>
</p>
<input type="submit" value="computeBMI" onclick="computeBMI();">
<div class="resultclass">
<h1>Your BMI is: <span id="output">?</span></h1>
<h1>This means you are: <span id="resultdiv">?</span></h1>
</div>
</body>
</html>
最佳答案
在您的 computeBMI() 函数中,您可以像这样将类设置为您想要的:
document.getElementById("resultdiv").className = "肥胖";
关于javascript - 使用 Javascript 更改 CSS 类以能够更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21836483/