使用JavaScript實現Input輸入數據后自動計算並實時顯示


代碼實現:

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
        <title>無標題</title>
        <script type="text/javascript">
        function sum(obj) {
var z = document.getElementById("z");
            var a = document.getElementById("a");
            var b = document.getElementById("b");
            var c = document.getElementById("c");
all.value=parseInt(z.value);
if(a.value!='')
{
y.value=parseInt(a.value);
h.value=parseInt(z.value)-parseInt(a.value);
}
if(a.value!=''&&b.value!='')
{
y.value=parseInt(b.value)+parseInt(a.value);
h.value=parseInt(z.value)-parseInt(a.value)-parseInt(b.value);
}
if(a.value!=''&&b.value!=''&&c.value!='')
{
y.value=parseInt(b.value)+parseInt(a.value)+parseInt(c.value);
h.value=parseInt(z.value)-parseInt(a.value)-parseInt(b.value)-parseInt(c.value);
}
        }
        </script>
    </head>
    <body>
總分:<input type="text" id="z" onkeyup="sum(this);" />
        <input type="text" id="a" onkeyup="sum(this);" />
        <input type="text" id="b" onkeyup="sum(this);" />
        <input type="text" id="c" onkeyup="sum(this);" />
總分:<input type='text' id='all' style="border:0px solid white; width:25px" />
已選:<input type='text' id='y' style="border:0px solid white; width:25px" />
還剩:<input type='text' id='h' style="border:0px solid white; width:25px" />
    </body>
 
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

效果實現:

在這里插入圖片描述

onkeyup:鍵盤按下的時候會觸發onkeydown,松開鍵盤時會出發onkeyup。

parseInt:parseInt() 函數可解析一個字符串,並返回一個整數。

parseInt("10");			//返回 10
parseInt("19",10);		//返回 19 (10+9)
  • 1
  • 2

原文:https://blog.csdn.net/qq_42249896/article/details/80963514


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM