Javascript-自动计算体重指数
为了计算体重指数,我有一个javascript,其中有两个输入字段用于身高和体重,一个输入字段用于显示计算结果 如何在BMI字段中自动显示che calc HTMlJavascript-自动计算体重指数,javascript,indexing,mass,Javascript,Indexing,Mass,为了计算体重指数,我有一个javascript,其中有两个输入字段用于身高和体重,一个输入字段用于显示计算结果 如何在BMI字段中自动显示che calc HTMl <h2>Height=<input type="text" id="hgt"></h2> <h2>Weight=<input type="text" id="wgt" onmouseout="bmi()"></h2> <h2>BMI=<in
<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>
函数bmi(){
var sheigh=parseFloat(document.getElementById('hgt').value);
var sweight=parseFloat(document.getElementById('wgt').value);
var bmi=sweight/Math.pow(Sheigh,2);
var student\u bmi=document.getElementById('student\u bmi')。值;
学生_bmi.textContent=bmi.toFixed(2);
}
在身高和体重字段中插入值后,不要在BMI字段中显示计算值
如何解决此问题?只有当鼠标位于元素内部时才会触发
onmouseout
事件,然后鼠标移出元素。在计算体重指数时,这似乎是一个奇怪的选择,因为在典型的用户操作过程中,鼠标可能不会移动到输入之外
一种更直接的方法是,每当上述两种输入的内容发生变化时,更新BMI。您还应该考虑在HTML中不使用内联JavaScript事件处理程序。这里有一种不同的方法:
HTML:
input
事件与mouseout
事件不同,它会为每次击键、粘贴或其他输入更改事件触发。您还可以使用change
事件或blur
,具体取决于您希望用户体验是什么样子。您的代码当前发生了什么?您应该始终发布预期与实际行为、控制台错误等。同时注意到您的HTML格式不正确;您没有关闭type=“text
属性;只是因为输入错误吗?这会导致错过id=“student\u bmi”
属性并导致document.getElementById('student\u bmi'))
调用不成功。抱歉,我已更新了脚本。当我写文章时,没有关闭类型。您预期的行为是什么?代码正在为onmouseout
事件计算BMI。这是您想要的,还是您想要其他的?在高度字段中插入值后,当鼠标移出时,在BMI fil中自动计算BMI谢谢你完美的回答
<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>
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 () {
const height = parseFloat(heightInput.value);
const weight = parseFloat(weightInput.value);
const bmi = weight / Math.pow(height, 2);
bmiInput.value = bmi.toFixed(2);
}