Javascript - 自动计算体重指数

为了计算身体质量指数,我有这个 javascript,其中有两个用于身高和体重的输入字段和一个用于显示计算输出的输入字段。


如何在 BMI 字段中自动显示 che calc?


商标


<h2>Height=<input type="text" id="hgt"></h2>


<h2>Weight=<input type="text" id="wgt" onmouseout="bmi()"></h2>


<h2>BMI=<input type="text" id="student_bmi">

Javascript


<script>

function bmi(){

var sheight=parseFloat(document.getElementById('hgt').value);

var sweight=parseFloat(document.getElementById('wgt').value);

var bmi=sweight/Math.pow(sheight,2);

var student_bmi=document.getElementById('student_bmi').value;

student_bmi.textContent=bmi.toFixed(2);

}

</script>

在 Height 和 Weight 字段中插入值后,不会在 BMI 字段中显示计算值。


如何解决这个问题?


人到中年有点甜
浏览 244回答 1
1回答

慕尼黑5688855

该onmouseout事件仅在鼠标位于元素内部时触发,然后鼠标移出元素。当您计算 BMI 时,这似乎是一个奇怪的选择,因为在典型的用户操作期间,鼠标可能不会移动到输入之外。一种更直接的方法是在上述两个输入中任何一个的内容发生变化时更新 BMI。您还应该考虑不在 HTML 中使用内联 JavaScript 事件处理程序。这是一种不同的方法:HTML:<h2>Height=<input type="text" id="hgt"></h2><h2>Weight=<input type="text" id="wgt"></h2><h2>BMI=<input type="text" id="student_bmi"></h2>JavaScript:const heightInput = document.getElementById('hgt');const weightInput = document.getElementById('wgt');const bmiInput = document.getElementById('student_bmi');heightInput.addEventListener('input', calculateBMI);weightInput.addEventListener('input', calculateBMI);function calculateBMI () {&nbsp; const height = parseFloat(heightInput.value);&nbsp; const weight = parseFloat(weightInput.value);&nbsp; const bmi = weight / Math.pow(height, 2);&nbsp; bmiInput.value = bmi.toFixed(2);}与input事件不同,该mouseout事件将在每次击键、粘贴或其他输入更改事件时触发。您还可以使用该change事件或blur取决于您希望用户体验的样子。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript