溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

javascript中怎么實(shí)現(xiàn)一個(gè)簡(jiǎn)易的計(jì)算器

發(fā)布時(shí)間:2021-07-06 16:52:05 來(lái)源:億速云 閱讀:141 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家介紹javascript中怎么實(shí)現(xiàn)一個(gè)簡(jiǎn)易的計(jì)算器,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

具體內(nèi)容如下

1、先構(gòu)思整個(gè)計(jì)算器的模式以及想要實(shí)現(xiàn)的功能,按模塊創(chuàng)建相應(yīng)的p,在“head”中設(shè)置其樣式和布局。2、用“input”標(biāo)簽創(chuàng)建text類(lèi)型,置為輸出框;依次創(chuàng)建buttom類(lèi)型,置為按鈕,內(nèi)容為1、2、3……;創(chuàng)建“=”,并在input中對(duì)他進(jìn)行點(diǎn)擊事件“οnclick=”result()””.3、添加script,利用var定義class里面的值,并賦值給一個(gè)新的變量,4、編寫(xiě)for循環(huán)語(yǔ)句,執(zhí)行代碼內(nèi)容5、最后添加result函數(shù),執(zhí)行結(jié)果。

源代碼如下(自行設(shè)置style的值):

<body><p class="contour">  <p class="screen">    <input class="text" type="text" value=''οnfοcus="this.blur();">  </p>  <p class="click">     <p>       <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='+'>     </p>     <p>       <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='-'>     </p>    <p>       <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='*'>     </p>     <p>       <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='/'>    </p>   </p></p>  <script>    var btnArr = document.getElementsByClassName("bt");    // var result=document.getElementById("result");    var text = document.getElementsByClassName("text")[0];    // console.log(btnArr)    // 用js給某一個(gè)元素添加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)于javascript中怎么實(shí)現(xiàn)一個(gè)簡(jiǎn)易的計(jì)算器就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI