javascript開發計算器之JS程式碼
前面介紹了HTML,下面我們主要說一下JS程式碼的寫法:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="format-detection" content="telephone=no" /> <title>计算器</title> <script type="text/javascript" src=""></script> <script> //点击按钮执行操作 var resultDom = document.getElementById("result"); //var 是定义变量, var operate = true; //定义一个变量,防止运算符的连续操作 var xop = true; //定义一个变量,防止小数点可以连续输出 function command(num){ //function 是封装command if(needclear==1){ needclear=0; resultDom.value=''; } var str = resultDom.value; str =(str =="0"?"":str); resultDom.value = str+num; operate = true; play(num); } //清空 function clearzero(m){ resultDom.value = 0; play(m) } //计算等号 var needclear=0; function equal(m){ needclear=1; var result = resultDom.value.toString(); var r = eval(result); resultDom.value =r; play(m); } //小数点 function dot(m){ if(xop){ //对变量进行判断输出 var num = resultDom.value.toString(); num +="."; resultDom.value = num; xop = ture; } play(m); } //点击操作符 function tools(op,m){ if(operate){ //对运算符进行判断输出 var num = resultDom.value; num = (num =="0"?"":num); resultDom.value = num+op; operate = false; } play(m); } //按键声音 function play(num){ var audioDom = document.getElementById("audio"); audioDom.innerHTML = "<embed src='wav/"+num+".wav' width='0' height='0'></embed>" //wav是声音素材的文件夹名称。 } </script> </body> </html>
每個功能都會有註解。由於語音素材無法上傳,所以知道寫法就可以了,可以自己上網下載聲音素材,自己試試看。