首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BMI计算程序

BMI计算程序
EN

Stack Overflow用户
提问于 2019-10-06 20:01:29
回答 3查看 355关注 0票数 0

我创建了一个计算BMI的应用程序。基本上,下面是我希望应用程序工作的方式,并且到目前为止我写了以下文章:

  • 您只需输入身高(以英寸为单位)并输入体重(以磅为单位)。
  • 应用程序将计算您的体重指数,然后告诉您您是体重不足、正常、肥胖还是超重。如果您输入一个非正值的身高或体重,该程序将显示一个错误消息:“无效输入。输入一个正数。”,它将突出显示需要修复/输入一个有效值的框。

我遇到了两个问题.

  • 我可以让程序显示BMI结果,但目前我不知道如何编写程序来显示用户是否体重不足、正常、肥胖或超重。如果BMI < 18.5,体重不足,BMI >= 18.5和<=24.99则正常,BMI > 25和<=29.99则肥胖,BMI > 30则超重。
  • I希望将错误(告诉用户输入正值,而不是缺失值或负值)显示为“计算体重指数”按钮下面的信息,而不是像“此页面上写的--输入的权重无效,输入一个非负数”这样的警告。换句话说,我希望保留相同的消息,但不要使用“警报”方法。

请问如何解决这些问题?我在下面附上了我的HTML和CSS代码。

非常感谢!

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>BMI Calculation</title>
    <link rel="stylesheet" href="bmi.css">

</head>
<body>
    <main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div class="results"></div>

    </main>     
    <script>
        var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var outputBMI = document.querySelectorAll("div.results");

             outputBMI[0].textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            ///get user input from input box "boxHeight" by using value property, 
            //which return user input as a string               
            //step1.1:get height input and convert height to a number
            var height = heightInputBox.value;
            height = parseFloat(height);

            //step1.2:get weight input and convert weight to a number
            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0) {
                alert("Invalid input for height, enter a non-negative number.");
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0) {
                alert("Invalid input for weight, enter a non-negative number.");
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }

            if (valid)          //calculate BMI
            {
                outputBMI[0].textContent  ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
            if (outputBMI[0]<18.5) outputBMI[0].textContent = "Your BMI indicates that you are underweight.";
            if (outputBMI[0]>=18.5 && outputBMI[0]<=24.99) document.getElementById("result").value = "Normal";
            if (outputBMI[0]>=25 && outputBMI[0]<=29.99) document.getElementById("result").value = "Obese";
            if (outputBMI[0]>30) document.getElementById("result").value = "Overweight";
            }
        };

        //add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
        document.getElementById('calculate').onclick = processEntries;

    </script>
</body>
</html>

这也是我的CSS代码,如果您需要的话:

代码语言:javascript
复制
article, aside, figure, footer, header, main, nav, section {
    display: block;
}
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;

}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}

div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;

}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
input.error {
    background-color: #FFFF00;
    border: 2px solid #fe9772;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-10-06 20:18:21

您的代码有很多需要重做的地方。但底线是,您需要记住,classSelector (在您的示例中是结果)总是返回一个数组。如果使用的是唯一的dom,则切换到Id

代码语言:javascript
复制
var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var resultElm = document.getElementById("result");

             resultElm.textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            ///get user input from input box "boxHeight" by using value property, 
            //which return user input as a string               
            //step1.1:get height input and convert height to a number
            var height = heightInputBox.value;
            height = parseFloat(height);

            //step1.2:get weight input and convert weight to a number
            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0) {
                alert("Invalid input for height, enter a non-negative number.");
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0) {
                alert("Invalid input for weight, enter a non-negative number.");
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }
            var bmi = 703 * weight / (height** 2)
            if (valid)          //calculate BMI
            {
                resultElm.textContent  ="Your BMI is: " + (bmi).toFixed(1);
                if (bmi<18.5) resultElm.textContent += " Your BMI indicates that you are underweight.";
                if (bmi>=18.5 && bmi<=25) resultElm.textContent += " Your BMI indicates that you are Normal.";
                if (bmi>=25 && bmi<=30)resultElm.textContent += " Your BMI indicates that you are Obese.";
                if (bmi>30) resultElm.textContent += " Your BMI indicates that you are Overweight";
            }
        };

        //add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
        document.getElementById('calculate').onclick = processEntries;
代码语言:javascript
复制
article, aside, figure, footer, header, main, nav, section {
    display: block;
}
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;

}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}

div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;

}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
input.error {
    background-color: #FFFF00;
    border: 2px solid #fe9772;
    }
代码语言:javascript
复制
<main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div id="result"></div>

    </main>

票数 1
EN

Stack Overflow用户

发布于 2019-10-07 05:35:44

我知道这个问题已经有了一个好的、有效的答案。

以下只是我玩弄小提琴的结果,试图缩短它,使它更“反应”。

我删除了计算按钮,现在使用eval()来容忍地转换和计算输入字段的值。

代码语言:javascript
复制
const qs=s=>document.querySelector(s);
evl=s=>{var v='', el=qs(s);
 try{v=eval(el.value)||''} catch(er){v=''}
 el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
 return v
}
var scale=[[18.5,"underweight"],
 [25,"normal"],[30,"obese"],
 [31,"seriously overweight"]];
 
qs("body").addEventListener("keyup",ev=>{if(ev.target.type!='text') return;
 var txt, height=evl("#boxHeight"), weight=evl("#boxWeight");
 if (height>0 && weight>0){
   BMI=703*weight/(height*height);
   scale.every(sc=>(txt=sc[1],BMI>sc[0])); 
   txt='Your BMI of '+BMI.toFixed(1)+" indicates<br>that you are "+txt+".";
 } else txt='';
 qs("#result").innerHTML=txt
 
});
代码语言:javascript
复制
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;
}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}
div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;
}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
span {margin-left:20px;
      font-size:1.5ex;}
代码语言:javascript
复制
<main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight' placeholder="value or formula"/><span id="one"></span><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight' placeholder="value or formula"/><span id="two"></span><br>
        <div id="result"></div>
    </main>

票数 0
EN

Stack Overflow用户

发布于 2019-10-07 15:13:48

过了一段时间,我编辑了我的代码几次,这是一个版本,我认为值得分享。我知道还有相当多的编辑要做--但这里是:

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>BMI Calculation</title>
    <link rel="stylesheet" href="bmi.css">

</head>
<body>
    <main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div class="results"></div>

    </main>     
    <script>
        var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var outputBMI = document.querySelectorAll("div.results");

             outputBMI[0].textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            var height = heightInputBox.value;
            height = parseFloat(height);

            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
                outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
                outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }

            if (valid)
            {
                outputBMI[0].textContent  ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);

                //This is just for my trial and learning process. =)
                var bmi = (703 * weight / (height*height)).toFixed(1);
                if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
                if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
                if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
                if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
            }
        };

       //handler button click event 
        document.getElementById('calculate').onclick = processEntries;

    </script>
</body>
</html>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58260804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档