Javascript eval not achieve calculator functions (b)

Has been optimized on the basis of a calculator on the first look at the effect
javascript calculator
this time the result is the region with the input tag
to view the structure of the code

<div id="box">
	<input id="value" type="text" value="0">
	<div>1</div>
	<div>2</div>
	<div>3</div>
	<div>4</div>
	<div>5</div>
	<div>6</div>
	<div>7</div>
	<div>8</div>
	<div>9</div>
	<div>0</div>
	<div>+</div>
	<div>-</div>
	<div>*</div>
	<div>/</div>
	<div>=</div>
	<div>c</div>
</div>

Style Code:

body,html,div{padding:0px;margin:0px;}
#box{width:320px;height:430px;padding:20px;border:1px solid #000;margin:30px auto;overflow:hidden;box-shadow:3px 3px 5px #ccc;}
#value{width:270px;height:40px;line-height:40px;font-size:30px;padding:5px 20px;border:1px solid #000;outline:none;text-align:right;display:block;margin:0px auto 10px;}
#box div{width:70px;height:70px;border:1px solid #000;float:left;margin:10px 10px 0px 0;line-height:70px;text-align:center;font-size:28px;user-select: none;cursor:pointer;box-shadow:2px 2px 4px #ccc;}
#box div:hover{box-shadow: -2px -2px 4px #ccc;}
#box div:nth-of-type(4n){margin-right:0px;}

Next is js code:

var input,num1,type;
init();
function init(){
    //获取input输入框
    input=document.getElementById("value");
    //获取div按键
    var divs=document.getElementById("box").getElementsByTagName("div");
    //给每个按键添加点击事件
    for(var i=0;i<divs.length;i++) divs[i].onclick=clickHand;
};

//点击事件
function clickHand(){
    switch(this.innerHTML){
        //判断如果是 + - * / ,则表示第一个数输入完毕
        case "+":
        case "-":
        case "*":
        case "/":
            //第一个数
            num1 = input.value;
            //运算符号
            type = this.innerHTML;
            //将value清空
            input.value = 0;
            break;
        case "=":
            //如果是等号,执行运算
            getCont();
            break;
        case "c":
            //如果是c,清空数据
            input.value = "0";
            num1 = 0;
            type = "";
            break;
        default:
            //赋值
            input.value=Number(input.value+this.innerHTML);
    }
}
//运算
function getCont(){
    switch(type){
        case "+":
            input.value =  Number(num1) + Number(input.value);
            break;
        case "-":
            input.value =  Number(num1) - Number(input.value);
            break;
        case "*":
            input.value =  Number(num1) * Number(input.value);
            break;
        case "/":
            //如果除数是0,则返回 输入错误
            input.value = input.value==0? "输入错误" :  Number(num1) / Number(input.value);
            break;
    }
}

The operation function and click function individually distinguished, so the code reusability stronger.

Published 46 original articles · won praise 26 · views 10000 +

Guess you like

Origin blog.csdn.net/Charissa2017/article/details/103765350