使用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; 25px" />
已选:<input type='text' id='y' style="border:0px solid white; 25px" />
还剩:<input type='text' id='h' style="border:0px solid white; 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

原文地址:https://www.cnblogs.com/apolloren/p/12146917.html