2018-11-10

简单计算器(JavaScript实现)

功能比较简单,还需完善。

效果:



HTML部分:

CSS部分:

.box{

border: 2px solid gray;

width: 450px;

height: 600px;

margin: auto auto;

border-radius: 10px;

}

input{

height: 200px;

width: 420px;

background-color: darkseagreen;

margin:auto auto;

margin-top: 10px;

position: relative;

top: 0px;

left: 15px;

font-size: 35px;

}

button{

background-color: orange;

padding: 20px  30px 20px 30px;

margin: 10px 30px 10px 0px;

font-size: 20px;

}

.first{

position: relative;

top: 0px;

left: 24px;

}

.bcolorr{

background-color: gray;

}

button:hover{

cursor: pointer;

box-shadow: 5px 5px 2px black;

}

button:active {

    box-shadow: 0 0 5px 5px dodgerblue;

}

JavaScript部分:

window.onload=function(){

var btn=document.getElementsByTagName('button');

var needClear=false;

var oshow=document.getElementById("show");

var number1="";

var operator="";

Array.prototype.forEach.call(btn,function(el){

console.log(el);/*el表示每一次访问的元素是谁,遍历所有按钮*/

el.onclick=doinput;

});

function doinput(){

var html=this.innerHTML;/*获取点击按钮的内容*/

switch(html)

{

case "=":

oshow.value=calc(number1*1,oshow.value*1,operator);

needClear=false;

break;

case "C":oshow.value=0;

needClear=false;//todo//

break;

case "+"://todo//

case "-"://todo//

case "x"://todo//

case "/"://todo//

if(number1.length!=0)

{

oshow.value=calc(number1*1,oshow.value*1,operator);

}

operator=html;//保存运算符

number1=oshow.value;//保存第一个运算数字

needClear=false;

break;

default://todo needClear bool值为true时执行

if(needClear){

oshow.value+=html;//拼接

}

else{

oshow.value=html;//替换

needClear=true;//替换完成后又变为true,然后执行拼接

}

break;

}

}

function calc(number1,number2,operator){

var result=0;//结果

switch (operator)

{

case "+":result=number1+number2;

break;

case "-":result=number1-number2;

break;

case "x":result=number1*number2;

break;

case "/":result=number1/number2;

break;

default:result=number2;

break;

}

return result;

}

}

你可能感兴趣的:(2018-11-10)