1. 程式人生 > >JavaScript制作簡單的計算器

JavaScript制作簡單的計算器

row 位置 onclick ava 例如 click border js計算 display

使用js來實現一個簡單的計算器功能,包括加減乘除以及清空內容。

下面的HTML的代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="jisuandiv"> <h2>js計算器</h2> <input type="text" id="text" value="" disabled="disabled"/> <br> <div id="jisuankuang"> <button type="button" onclick="cale(this.id)" id="7" value="7">7</button> <button type="button" onclick="cale(this.id)" id="8" value="8">8</button> <button type="button" onclick="cale(this.id)" id="9" value="9">9</button> <button type="button" onclick="cale(this.id)" id="*" value="*">*</button> <button type="button" onclick="cale(this.id)" id="4" value="4">4</button> <button type="button" onclick="cale(this.id)" id="5" value="5">5</button> <button type="button" onclick="cale(this.id)" id="6" value="6">6</button> <button type="button" onclick="cale(this.id)" id="/" value="/">/</button> <button type="button" onclick="cale(this.id)" id="1" value="1">1</button> <button type="button" onclick="cale(this.id)" id="2" value="2">2</button> <button type="button" onclick="cale(this.id)" id="3" value="3">3</button> <button type="button" onclick="cale(this.id)" id="-" value="-">-</button> <button type="button" onclick="jieguo()" id="=" value="">=</button> <button type="button" onclick="cale(this.id)" id="0" value="0">0</button> <button type="button" onclick="C()" id="C" >C</button> <button type="button" onclick="cale(this.id)" id="+" value="+">+</button> </div> </div> </body> </html>


css代碼:

#jisuandiv{
        height: 460px;
        width: 300px;
        background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898; background-blend-mode: multiply,multiply;
    }
    #jisuandiv>h2{
        text-align: center; 
    }
    #jisuandiv>input{
        display: block;
        height: 60px;
        width: 260px;
        line-height: 60px;
        font-size: 40px;
        margin: 0 auto;
        text-align: center;
    }
    #jisuankuang{
        margin: 0 auto;
        height: 300px;
        width: 260px;
        border: white 4px solid;
        display: flex;
        flex-flow: row wrap;
        justify-content: space-around;
    }
    #jisuankuang>button{
        margin: 6px;
        width: 50px;
        height: 50px;
        background: red;
        font-size: 16px;
    }```

js代碼:

// 獲取輸入數字
function cale(num){
document.getElementById("text").value +=document.getElementById(num).value;
}
// 計算結果
function jieguo(){
var str= document.getElementById("text").value;
document.getElementById("text").value = eval(str);
}
function C(){
document.getElementById("text").value ="";

}
```

簡單的功能,希望能幫助到需要的人,這裏代碼的重點是運用js中的函數 eval,它主要可以讓string字符串進行計算,例如:eval("2+2");
其他功能只要能獲得按鈕的參數,並累加給顯示的位置即可。

JavaScript制作簡單的計算器