javascript - 使用 Javascript 更改 CSS 类以能够更改颜色

标签 javascript html css

我正在创建一个 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/

相关文章:

javascript - 无论文本/跨浏览器支持如何,都使按钮大小相同

javascript - 如何读取 pm api sendRequest 生成的流响应

php - 如何获取 SELECT OPTION 的选定值

html - CSS 中的对齐问题

php - IE8 不允许下拉菜单

javascript - Jquery 移动版 - 1.4.2 : general documentation lakes?

javascript - 如何在phaserjs中使用混合

jquery - 如何在 jquery 中使用选项卡?

javascript - 无法在 &lt;script&gt; 标签上对生成的 RSS 进行样式化

html - 如何阻止文本占用超过 1 行?