js實現簡單的計算器
阿新 • • 發佈:2018-11-19
js實現一個簡單的計算器,有加減乘除的基本功能。
首先使用HTML寫一個介面,需要三個文字框,包括兩個輸入框,一個輸出框,輸出框不能被操作,還需要一個選擇框,用來選擇運算子,最後還需要兩個按鈕,等於按鈕以及清零按鈕。
選擇框使用標籤select
輸出按鈕不能被操作則應使用屬性disabled="true"
清零功能則使用reset,可以清零整個表單,不過對其他表單的內容沒有影響
接著需要使用CSS調整樣式,對整體進行美化,新增背景顏色,設定其長度和寬度
然後使用js實現其功能:先獲得兩個輸入框的值以及選擇框的運算子,將得到的輸入框的值轉為Number型,然後對其進行操作運算。
程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="css/com.css" /> </head> <body> <div id="computer"> <form> <input id="text1" type="text" /> <select id="select"> <option>+</option> <option>-</option> <option>*</option> <option>/</option> </select> <input id="text2" type="text" /> <script type="text/javascript" src="js/com.js"></script> <input id="button" type="button" value="=" onclick="computer();"/> <input id="text3" disabled="true" type="text" /> <input id="button1" type="reset" value="清零" /> </form> </div> </body> </html>
*{ margin: 0; padding: 0; } #computer{ width: 700px; height: 40px; padding-top: 25px; padding-left: 15px; } #computer input{ height: 30px; width: 100px; } #button{ background-color:burlywood; } #button1{ background-color:burlywood; margin-left: 50px; } #text1,#text2{ text-align: center; background-color: beige; } #text3{ text-align: center; background-color: aliceblue; }
function computer(){
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
var select = document.getElementById("select").value;
// 將value轉為數字Number()或parseInt()
var resu;
if(select=="+"){
resu = Number(text1) + Number(text2);
}else if(select=="-"){
resu = Number(text1) - Number(text2);
}else if(select=="*"){
resu = Number(text1) * Number(text2);
}else if(select=="/"){
resu = Number(text1) / Number(text2);
}
document.getElementById("text3").value=resu;
}