纯Js(3个输入实时计算)?

时间:2018-08-22 06:50:32

标签: javascript html

构建一个基本的计算器。

<html>    
<body>

    <input class="numb1" type=number name="secondBox" value="">

    <input class="numb2" type=number name="secondBox" value="">

    <input class="numb3" type=number name="thirdBox" value="" readonly>

</body>    
</html>  

2 个答案:

答案 0 :(得分:0)

这是一个有效的示例:

window.addEventListener("load",function() { 
  setInterval(function() {
    document.getElementById("stat").innerHTML=localStorage.getItem("value") || "nothing yet";
  }, 500);
});
var evN1  = document.getElementById("no1Box");
evN1.addEventListener("input", calculate, false);
var evN2  = document.getElementById("no2Box");
evN2.addEventListener("input", calculate, false);


function calculate() {

  var n1 = document.getElementById("no1Box").value;
  var n2 = document.getElementById("no2Box").value;
  var r = n1/n2;

  document.getElementById("result").innerHTML = "Result: " + r;
  
}

 
body {padding:0;margin:0;font-family:Arial,Helvetica,sans-serif;}
div {margin:15px;}
label {display:block;}
input {border:solid 1px #888;font-size:20px;border-radius:5px;padding:2px;outline:none;}
.myInput {box-shadow:0 0 4px green;}

通过<!DOCTYPE html> <html> <body> <label for="input">Input 1</label> <input class="myInput" id="no1Box" type=number name="firstBox" value=""> <label for="input">Input 2</label> <input class="myInput" id="no2Box" type=number name="secondBox" value=""> <p id="result"/> </body> </html>,将元素与您在html see more about getElementById here上设置的唯一ID一起使用,并通过使用document.getElementById("no1Box");获得在输入​​中引入的值。

在使用元素.value之后,向他var evN2 = document.getElementById("no2Box");添加一个侦听器,并告知更改输入后应执行什么功能。 more examples for eventListener here

如果您有任何疑问,请随时提问。

答案 1 :(得分:0)

    <html><input type='number' id='one' placeholder='00' onblur='calculate()'>
    &nbsp; &nbsp; / &nbsp; &nbsp;
    <input type='number' id='two' placeholder='00' oninput='calculate()'>
    <input type='number' id='result' placeholder='Result' disabled>

    <script>
    function calculate(){
        var one = document.querySelector('#one').value;
        var two = document.querySelector('#two').value;
        var result = document.querySelector('#result');
        result.value = Math.floor(one/two);
    }
    </script>
</html>