javascript實現(xiàn)簡易的計算器
利用javascript實現(xiàn)簡易的計算器,供大家參考,具體內(nèi)容如下
1、先構(gòu)思整個計算器的模式以及想要實現(xiàn)的功能,按模塊創(chuàng)建相應(yīng)的div,在“head”中設(shè)置其樣式和布局。
2、用“input”標(biāo)簽創(chuàng)建text類型,置為輸出框;依次創(chuàng)建buttom類型,置為按鈕,內(nèi)容為1、2、3……;創(chuàng)建“=”,并在input中對他進(jìn)行點(diǎn)擊事件“οnclick=”result()””.
3、添加script,利用var定義class里面的值,并賦值給一個新的變量,
4、編寫for循環(huán)語句,執(zhí)行代碼內(nèi)容
5、最后添加result函數(shù),執(zhí)行結(jié)果。
源代碼如下(自行設(shè)置style的值):
<body><div class="contour"> <div class="screen"> <input class="text" type="text" value=''οnfοcus="this.blur();"> </div> <div class="click"> <div> <input class="bt t" type="button" value="1"> <input class="bt t" type="button" value='2'> <input class="bt t" type="button" value='3'> <input class="bt t" type="button" value='+'> </div> <div> <input class="bt t" type="button" value='4'> <input class="bt t" type="button" value='5'> <input class="bt t" type="button" value='6'> <input class="bt t" type="button" value='-'> </div> <div> <input class="bt t" type="button" value='7'> <input class="bt t" type="button" value='8'> <input class="bt t" type="button" value='9'> <input class="bt t" type="button" value='*'> </div> <div> <input class="bt t" type="button" value='#'> <input class="bt t" type="button" value='0'> <input id="result" class="t" type="button" value='=' onclick="result()"> <input class="bt t" type="button" value='/'> </div> </div> </div> <script> var btnArr = document.getElementsByClassName("bt"); // var result=document.getElementById("result"); var text = document.getElementsByClassName("text")[0]; // console.log(btnArr) // 用js給某一個元素添加click事件 // btnArr[0].οnclick=function(){ // alert() // } // for循環(huán)添加click事件 // input的value指的是 input的值 var showNum='' //alert(btnArr[1].value); for(var i=0;i<btnArr.length;i++){ btnArr[i].οnclick=function(){ showNum =showNum+this.value; text.value = showNum; } } function result(){ text.value=eval(showNum) } </script> </body>
關(guān)于計算器的精彩文章請查看《計算器專題》 ,更多精彩等你來發(fā)現(xiàn)!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
layui表單驗證select下拉框?qū)崿F(xiàn)驗證的方法
今天小編就為大家分享一篇layui表單驗證select下拉框?qū)崿F(xiàn)驗證的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09js表格排序?qū)嵗治觯ㄖС謎nt,float,date,string四種數(shù)據(jù)類型)
這篇文章主要介紹了js表格排序?qū)嵗治觯ㄖС謎nt,float,date,string四種數(shù)據(jù)類型),涉及javascript常用的升序、降序及數(shù)據(jù)類型轉(zhuǎn)換等相關(guān)技巧,需要的朋友可以參考下2015-05-05ajaxControlToolkit AutoCompleteExtender的用法
昨天在搜索中使用了這個控件,不過不知道為什么在IE中反應(yīng)比較慢2008-10-10JS使用cookie實現(xiàn)DIV提示框只顯示一次的方法
這篇文章主要介紹了JS使用cookie實現(xiàn)DIV提示框只顯示一次的方法,涉及JavaScript基于cookie標(biāo)記控制頁面元素樣式修改的技巧,需要的朋友可以參考下2015-11-11jstree中的checkbox默認(rèn)選中和隱藏示例代碼
這篇文章主要介紹了jstree的checkbox默認(rèn)選中和隱藏,需要的朋友可以參考下2019-12-12