1 回答

TA貢獻1848條經(jīng)驗 獲得超2個贊
該onmouseout事件僅在鼠標位于元素內(nèi)部時觸發(fā),然后鼠標移出元素。當您計算 BMI 時,這似乎是一個奇怪的選擇,因為在典型的用戶操作期間,鼠標可能不會移動到輸入之外。
一種更直接的方法是在上述兩個輸入中任何一個的內(nèi)容發(fā)生變化時更新 BMI。您還應該考慮不在 HTML 中使用內(nèi)聯(lián) 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事件將在每次擊鍵、粘貼或其他輸入更改事件時觸發(fā)。您還可以使用該change事件或blur取決于您希望用戶體驗的樣子。
添加回答
舉報