我有 3 个输入字段。当我将鼠标从第三个输入字段移开时,3个输入字段值的总和应填充到第四个输入字段中(保持只读)。如何使用 html 和 javascript 做到这一点?
一只甜甜圈
浏览 121回答 3
3回答
收到一只叮咚
您可以使用onmouseout事件来获取所有三个字段的总和。首先创建一个方法getSum并使用它onmouseout来执行。function getSum(){ //Fetch value from all input fields let first = document.getElementById('field1').value; let second = document.getElementById('field2').value; let third = document.getElementById('field3').value; let fourth = document.getElementById('field4'); //Calculate the sum let sum = Number(first)+Number(second)+Number(third); //Assign the sum to the fourth field field4.value = sum; }<!DOCTYPE html> <html> <body> <h3>Enter Number:</h3> <label>First:</label> <br> <input type="number" id="field1"> <br> <label>Second:</label> <br> <input type="number" id="field2"> <br> <label>Third:</label> <br> <input type="number" id="field3" onmouseout="getSum()"> <br> <label>Sum:</label> <br> <input type="number" id="field4" disabled> </body> </html>