1 回答

TA贡献1848条经验 获得超2个赞
该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 () {
const height = parseFloat(heightInput.value);
const weight = parseFloat(weightInput.value);
const bmi = weight / Math.pow(height, 2);
bmiInput.value = bmi.toFixed(2);
}
与input事件不同,该mouseout事件将在每次击键、粘贴或其他输入更改事件时触发。您还可以使用该change事件或blur取决于您希望用户体验的样子。
添加回答
举报