導航:首頁 > 編程語言 > js製作簡易計算器實例

js製作簡易計算器實例

發布時間:2023-02-18 16:11:20

『壹』 如何使用js編寫一個簡單的計算器

js部分
var num=0,result=0,numshow="0";
var operate=0; //判斷輸入狀態的標志
var calcul=0; //判斷計算狀態的標志
var quit=0; //防止重復按鍵的標志
function command(num){
var str=String(document.calculator.numScreen.value); //獲得當前顯示數據
str=(str!="0") ? ((operate==0) ? str : "") : ""; //如果當前值不是"0",且狀態為0,則返回當前值,否則返回空值;
str=str + String(num); //給當前值追加字元
document.calculator.numScreen.value=str; //刷新顯示
operate=0; //重置輸入狀態
quit=0; //重置防止重復按鍵的標志
}
function dzero(){
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? ((operate==0) ? str + "00" : "0") : "0"; //如果當前值不是"0",且狀態為0,則返回當str+"00",否則返回"0";
document.calculator.numScreen.value=str;
operate=0;
}
function dot(){
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? ((operate==0) ? str : "0") : "0"; //如果當前值不是"0",且狀態為0,則返回當前值,否則返回"0";
for(i=0; i<=str.length;i++){ //判斷是否已經有一個點號
if(str.substr(i,1)==".") return false; //如果有則不再插入
}
str=str + ".";
document.calculator.numScreen.value=str;
operate=0;
}
function del(){ //退格
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? str : "";
str=str.substr(0,str.length-1);
str=(str!="") ? str : "0";
document.calculator.numScreen.value=str;
}
function clearscreen(){ //清除數據
num=0;
result=0;
numshow="0";
document.calculator.numScreen.value="0";
}
function plus(){ //加法
calculate(); //調用計算函數
operate=1; //更改輸入狀態
calcul=1; //更改計算狀態為加
}
function minus(){ //減法
calculate();
operate=1;
calcul=2;
}
function times(){ //乘法
calculate();
operate=1;
calcul=3;
}
function divide(){ //除法
calculate();
operate=1;
calcul=4;
}
function persent(){ //求余
calculate();
operate=1;
calcul=5;
}
function equal(){
calculate(); //等於
operate=1;
num=0;
result=0;
numshow="0";
}
//
function calculate(){
numshow=Number(document.calculator.numScreen.value);
if(num!=0 && quit!=1){ //判斷前一個運算數是否為零以及防重復按鍵的狀態
switch(calcul){ //判斷要輸入狀態
case 1:result=num+numshow;break; //計算"+"
case 2:result=num-numshow;break; //計算"-"
case 3:result=num*numshow;break;
case 4:if(numshow!=0){result=num/numshow;}else{document.getElementById("note").innerHTML="被除數不能為零!"; setTimeout(clearnote,4000)} break;
case 5:result=num%numshow;break;
}
quit=1; //避免重復按鍵
}
else{
result=numshow;
}
numshow=String(result);
document.calculator.numScreen.value=numshow;
num=result; //存儲當前值
}
function clearnote(){ //清空提示
document.getElementById("note").innerHTML="";
}

html部分:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>寫給新手:js表單操作(四) 簡單計算器(二)</title>
<style type="text/css">
body {
font-size:12px;
font-family:Arial, Georgia, "Times New Roman", Times, serif;
color:#555;
text-align:center;
background-color:#e2e2e2;
}
h6{
margin:0;
font-size:12px;
}
#calculator {
width:240px;
height:auto;
overflow:hidden;
margin:10px auto;
border:#fff 1px solid;
padding-bottom:10px;
background-color:#f2f2f2;
}
#calculator div {
clear:both;
}
#calculator ul{
padding:0;
margin:5px 14px;
border:#fff 1px solid;
height:auto;
overflow:hidden
}
#calculator li{
list-style:none;
float:left;
width:32px;
height:32px;
margin:5px;
display:inline;
line-height:32px;
font-size:14px;
background-color:#eaeaea;
}
#calculator li.tool{
background-color:#e2e2e2;
}
#calculator li:hover{
background-color:#f9f9f9;
cursor:pointer;
}
#calculator li:active{
background-color:#fc0;
cursor:pointer;
}
#calculator li.tool:active{
background-color:#d8e8ff;
cursor:pointer;
}
#calcu-head {
text-align:left;
padding:10px 15px 5px;
}
span.imyeah {
float:right;
color:#ccc;
}
span.imyeah a{
color:#ccc;
}
.screen{
width:200px;
height:24px;
line-height:24px;
padding:4px;
border:#e6e6e6 1px solid;
border-bottom:#f2f2f2 1px solid;
border-right:#f2f2f2 1px solid;
margin:10px auto;
direction:ltr;
text-align:right;
font-size:16px;
color:#999;
}
#calcu-foot{
text-align:left;
padding:10px 15px 5px;
height:auto;
overflow:hidden;
}
span#note{
float:left;
width:210px;
height:auto;
overflow:hidden;
color:red;
}
span.welcome{
clear:both;
color:#999;
}
span.welcome a{
float:right;
color:#999;
}
</style>
<script language="javascript">
//此處插入上面的js代碼
</script>
</head>
<body>
<div id="calculator">
<div id="calcu-head"><span class="imyeah">© <a href="http://www.cnblogs.com/imyeah/" target="_blank">I'm Yeah!</a></span><h6>簡單的計算器</h6></div>
<form name="calculator" action="" method="get">
<div id="calcu-screen">
<!--配置顯示窗口,使用onfocus="this.blur();"避免鍵盤輸入-->
<input type="text" name="numScreen" class="screen" value="0" onfocus="this.blur();" />
</div>
<div id="calcu-btn">
<ul> <!--配置按鈕-->
<li onclick="command(7)">7</li>
<li onclick="command(8)">8</li>
<li onclick="command(9)">9</li>
<li class="tool" onclick="del()">←</li>
<li class="tool" onclick="clearscreen()">C</li>
<li onclick="command(4)">4</li>
<li onclick="command(5)">5</li>
<li onclick="command(6)">6</li>
<li class="tool" onclick="times()">×</li>
<li class="tool" onclick="divide()">÷</li>
<li onclick="command(1)">1</li>
<li onclick="command(2)">2</li>
<li onclick="command(3)">3</li>
<li class="tool" onclick="plus()">+</li>
<li class="tool" onclick="minus()">-</li>
<li onclick="command(0)">0</li>
<li onclick="dzero()">00</li>
<li onclick="dot()">.</li>
<li class="tool" onclick="persent()">%</li>
<li class="tool" onclick="equal()">=</li>
</ul>
</div>
<div id="calcu-foot">
<span id="note"></span>
<span class="welcome">歡迎使用javascript計算器!<a href="http://www.cnblogs.com/imyeah" target="_blank">反饋</a></span>
</div>
</form>
</div>
</body>
</html>

『貳』 js計算器代碼怎麼寫,通過彈窗顯示

js計算器代碼,通過彈窗顯示步驟如下。
1、js計算器代碼編寫html,實現計算器頁面視圖效果。
2、js計算器代碼編寫,實現點擊輸入數字和符號輸出結果。
3、js計算器代碼創建click1函數,判斷flag的值,如果是true就定位到第一個輸入框,如果是false就定位到第二個輸入框,將點擊傳過來的值與輸入框裡面的字元串拼接到一起。
4、js計算器代碼定義result函數,定位到兩個輸入框,取出其中的值並轉成整數,定位到隱藏輸入框,取出裡面的符號,然後判斷是什麼符號,進行相應的運算,彈出運算結果。

『叄』 做一個簡易js計算器

正好今天有人想讓我幫他做個計算器,我就寫了一個

但是比你要的這個復雜一些你可以參考一下:

<style type="text/css">
.calculator{width:160px;height:180px;border:1px solid #ccc;}
.calculator h1{font-size:12px;font-weight:bold;background-color:#ccc;padding:0;margin:0;height:20px;line-height:20px;}
.calculator input{width:140px;height:20px;margin:2px 4px;}
.calculator table{width:100%;}
.calculator table button{width:100%;height:100%;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" >
function Calculator(){
this.a = null;
this.b = null;
this.symbol = null;
//狀態:0代表等待輸入第一個數,1代表輸入了操作符,2代表等待輸入第2個數
this.status = 0;

this.$div = $("<div class=\"calculator\"><h1>計算器</h1></div>");
this.$input = $("<input type=\"text\" value=\"0\">").appendTo(this.$div);
this.$table = $("<table><tbody></tbody></table>").appendTo(this.$div);
var btns = [
["+","-","*","/"],
["9","8","7","0"],
["4","5","6","C"],
["1","2","3","="]
];
for(var i=0;i<btns.length;i++){
var $tr = $("<tr></tr>");
for(var j=0;j<btns[i].length;j++){
$tr.append($("<td></td>").append(
$("<button type=\"button\">"+btns[i][j]+"</button>").click({"cal":this,"cmd":btns[i][j]},function(e){
e.data["cal"].command(e.data["cmd"]);
})
));
}
this.$table.find(">tbody").append($tr);
}

this.operations = {
"+":function(a,b){return parseInt(a,10)+parseInt(b,10);},
"-":function(a,b){return parseInt(a,10)-parseInt(b,10);},
"*":function(a,b){return parseInt(a,10)*parseInt(b,10);},
"/":function(a,b){return parseInt(a,10)/parseInt(b,10);}
};

this.command = function(str){
var inputtext = this.$input.val();
if((/[0-9]/.test(str))){//輸入數字時
if(this.status == 1 ){
this.$input.val(str);
this.status = 2;
}else{
if(this.$input.val()=="0"){
this.$input.val(str);
}else{
this.$input.val(inputtext+str);
}
}
}else if(/[\+\-\*\/]/.test(str)){//輸入加減乘除時
if(this.status == 0){
this.a = inputtext;
this.symbol = str;
this.status = 1;
}else if(this.status==1){
this.symbol = str;
}else if(this.status==2){
this.b = inputtext;
var val = this.operations[this.symbol](this.a,this.b);
this.$input.val(val+"");
this.status = 1;
this.a = val;
this.symbol = str;
}
}else if(str=="C"){//輸入清空時
this.a = null;
this.b = null;
this.symbol = null;
this.status = 0;
this.$input.val("0");
}else if(str=="="){//輸入等於時
if(this.status==2){
this.b = inputtext;
var val = this.operations[this.symbol](this.a,this.b);
this.$input.val(val+"");
this.status = 0;
this.a = val;
}
}
}
}
$(function(){
var myCal = new Calculator();
$("#aaa").append(myCal.$div);
});
</script>
<div id="aaa"></div>

『肆』 如何用js做一個簡易計算器

js做一個簡易計算器具體如下:

『伍』 用js代碼做一個簡易計算器

functiontest(){
vartxt1=document.getElementById("txt1"),
txt2=document.getElementById("txt2"),
txt3=document.getElementById("txt3"),
opt=document.getElementById("sel");
txt3.value=eval(txt1.value+opt.value+txt2.value);//eval函數可計算某個字元串,並執行其中的的js代碼
}
<inputtype="text"id="txt1"/>
<selectid="sel">
<optionvalue="+">+</option>
<optionvalue="-">-</option>
<optionvalue="*">*</option>
<optionvalue="/">/</option>
</select>
<inputtype="text"id="txt2"/>
=
<inputtype="text"id="txt3"/>
<inputtype="button"id="btn"value="計算"onclick="test()"/>

『陸』 用JavaScript做一個簡易的計算器

我剛學javaScript做一計算器,請看看!多多交流!~~``

<html>
<head>
<title>計算器</title>
</head>
<body bgcolor="#33FF99" onload="FKeyPad.ReadOut.focus();FKeyPad.ReadOut.select();">
<FORM name="Keypad" action="">
<TABLE align="center">
<B>
<TABLE align="center" border=3 width=60 height=80 cellpadding=2 cellspacing=5 borderlight="#008080">
<tr align="center">
<td bordercolor="#FF33CC" bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933" colspan=10 align=center>網頁計算器</td>
</tr>
<tr align="center">
<td bordercolor="#FF33CC" bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933" colspan=10 align=right><input name="ReadOut" type="Text" onkeypress="CheckOut()" size=40 value="0"
width=100%></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnsin" type="Button" value=" sin " onclick="useFun ('sin')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btncos" type="Button" value=" cos " onclick="useFun ('cos')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnOne" type="Button" value=" 1 " onclick="NumPressed(1)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnTwo" type="Button" value=" 2 " onclick="NumPressed(2)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnThree" type="Button" value=" 3 " onclick="NumPressed(3)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnPlus" type="Button" value=" + " onclick="Operation('+')"> </td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnasin" type="Button" value=" asin " onclick="useFun ('asin')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnacos" type="Button" value=" acos " onclick="useFun ('acos')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnFour" type="Button" value=" 4 " onclick="NumPressed(4)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnFive" type="Button" value=" 5 " onclick="NumPressed(5)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnSix" type="Button" value=" 6 " onclick="NumPressed(6)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnMinus" type="Button" value=" - " onclick="Operation('-')"></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btntan" type="Button" value=" tan " onclick="useFun ('tan')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnatan" type="Button" value=" atan " onclick="useFun ('atan')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnSeven" type="Button" value=" 7 " onclick="NumPressed(7)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnEight" type="Button" value=" 8 " onclick="NumPressed(8)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnNine" type="Button" value=" 9 " onclick="NumPressed(9)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnMultiply" type="Button" value=" * " onclick="Operation('*')"></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnlog" type="Button" value=" log " onclick="useFun ('log')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnexp" type="Button" value=" exp " onclick="useFun ('exp')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnZero" type="Button" value=" 0 " onclick="NumPressed(0)"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDecimal" type="Button" value=" . " onclick="Decimal()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnNeg" type="Button" value=" +/- " onclick="Neg()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDivide" type="Button" value=" / " onclick="Operation('/')"></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnsqrt" type="Button" value=" sqrt " onclick="useFun ('sqrt')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnOx" type="Button" value=" 1/x " onclick="useFun ('1/x')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnXt" type="Button" value=" x^2 " onclick="useFun ('x^2')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnXthr" type="Button" value=" x^3 " onclick="useFun ('x^3')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnpi" type="Button" value=" pi " onclick=FKeyPad.ReadOut.value=Math.PI></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnEquals" type="Button" value=" = " onclick="Operation('=')"></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDivide" type="Button" value=" N! " onclick="ni ()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDivide" type="Button" value=" pow " onclick="Operation('pow')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDivide" type="Button" value=" E " onclick=FKeyPad.ReadOut.value=Math.E></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnClear" type="Button" value=" C " onclick="Clear()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnClearEntry" type="Button" value=" CE " onclick="ClearEntry()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnReturn" type="Button" value="返 回" onclick="goReturn()"></td>
</tr>
<tr align="center">
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnmod" type="Button" value=" MOD " onclick="Operation('MOD')"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnDivide" type="Button" value=" INT" onclick=FKeyPad.ReadOut.value=parseInt(FKeyPad.ReadOut.value,10)></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnmod" type="Button" value=" HEX " onclick="hexchange ()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnmod" type="Button" value=" OCT " onclick="octchange ()"></td>
<td bordercolordark="#cc0066" bordercolor="#FF9966" bordercolorlight="#CC9933"><input name="btnmod" type="Button" value=" BIN " onclick="binchange ()"></td>
</tr>
</TABLE>
</TABLE>
</B>
</FORM>
</CENTER>
<font face="Verdana, Arial, Helvetica" size=2>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var FKeyPad = document.forms['Keypad'];
var Accum = "0";
var FlagNewNum = false;
var PendingOp = "";
function longCount(str1,str2,type)
{
var comma1 = 0;
if (str1.indexOf(".")!=-1)
{
str1 = str1.replace(/0*$/,"");
comma1 = str1.length - str1.indexOf(".")-1;
}
var comma2 = 0;
if (str2.indexOf(".")!=-1)
{
str2 = str2.replace(/0*$/,"");
comma2 = str2.length - str2.indexOf(".")-1;
}
str1 = str1.replace(/\./,"");
str2 = str2.replace(/\./,"");
var value,comma;
if (type!="*")
{
if (comma1>comma2)
{
for (var i=0;i<comma1-comma2;i++) str2 += "0";
comma = (type=="/")?0:comma1;
}else
{
for (var i=0;i<comma2-comma1;i++) str1 += "0";
comma = (type=="/")?0:comma2;
}
}else
{
comma = comma1 + comma2;
}
if (type=="+")
{
value = parseInt(str1,10) + parseInt(str2,10);
}else if (type=="-")
{
value = parseInt(str1,10) - parseInt(str2,10);
}else if (type=="*")
{
value = parseInt(str1,10) * parseInt(str2,10);
}else if (type=="/")
{
value = parseInt(str1,10) / parseInt(str2,10);
}
else if (type=="MOD")
value = parseInt(str1,10) % parseInt(str2,10);
else if (type=="pow")
{
var a,b,s=1;
a=parseInt(str1,10);
b=parseInt(str2,10);
for(var i=1;i<=b;i++)
s=s*a;
value=parseInt(s,10);
}
value = String(value);
if (comma>0) value = value.substring(0,value.length-comma)+"."+value.substring(value.length- comma,value.length);
if (value.indexOf(".")!=-1)
value = value.replace(/0*$/,"");
return value;
}
function NumPressed (Num) {
if (FlagNewNum)
{
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
}
else
{
if (FKeyPad.ReadOut.value == "0")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
function Operation (Op)
{
var Readout = FKeyPad.ReadOut.value;
if (FlagNewNum && PendingOp != "=");
else
{
FlagNewNum = true;
if ( '+' == PendingOp || '-' == PendingOp || '/' == PendingOp || '*' == PendingOp||'MOD'==PendingOp||'pow'==PendingOp)
Accum = longCount(Accum,Readout,PendingOp);
else
Accum = Readout;
FKeyPad.ReadOut.value = Accum;
PendingOp = Op;
FKeyPad.ReadOut.focus();
FKeyPad.ReadOut.select();
}
}
function useFun (st)
{
switch(st)
{
case "sin":
FKeyPad.ReadOut.value=Math.sin(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "cos":
FKeyPad.ReadOut.value=Math.cos(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "asin":
FKeyPad.ReadOut.value=Math.asin(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "acos":
FKeyPad.ReadOut.value=Math.acos(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "tan":
FKeyPad.ReadOut.value=Math.tan(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "atan":
FKeyPad.ReadOut.value=Math.atan(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "log":
FKeyPad.ReadOut.value=Math.log(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "exp":
FKeyPad.ReadOut.value=Math.exp(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "sqrt":
FKeyPad.ReadOut.value=Math.sqrt(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "1/x":
FKeyPad.ReadOut.value=1/FKeyPad.ReadOut.value;
FlagNewNum=true;
break;
case "x^2":
FKeyPad.ReadOut.value=parseFloat(FKeyPad.ReadOut.value)*parseFloat(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;
case "x^3":
FKeyPad.ReadOut.value=parseFloat(FKeyPad.ReadOut.value)*parseFloat(FKeyPad.ReadOut.value)*parseFloat(FKeyPad.ReadOut.value);
FlagNewNum=true;
break;

}

}
function hexchange ()
{
var hex,dec;
dec = parseFloat(FKeyPad.ReadOut.value);
hex = dec.toString(16);
window.alert("該十進制數轉成十六進制數為:"+ hex);
}
function octchange ()
{
var oct,dec;
dec = parseFloat(FKeyPad.ReadOut.value);
oct = dec.toString(8);
window.alert("該十進制數轉成八進制數為:"+ oct);
}
function binchange ()
{
var bin,dec;
dec = parseFloat(FKeyPad.ReadOut.value);
bin = dec.toString(2);
window.alert("該十進制數轉成二進制數為:"+ bin);
}
function ni ()
{var y,k=1;
y=parseFloat(FKeyPad.ReadOut.value);
for(var x=1;x<=y;x++)
k=k*x;
FKeyPad.ReadOut.value=k;
}
function Decimal ()
{
var curReadOut = FKeyPad.ReadOut.value;
if (FlagNewNum)
{
curReadOut = "0.";
FlagNewNum = false;
}
else
{
if (curReadOut.indexOf(".") == -1)
curReadOut += ".";
}
FKeyPad.ReadOut.value = curReadOut;
}
function ClearEntry ()
{
FKeyPad.ReadOut.value = "0";
FlagNewNum = true;
}
function Clear ()
{
Accum = "0";
PendingOp = "";
ClearEntry();
}
function Neg ()
{
window.alert(FKeyPad.ReadOut.value);
FKeyPad.ReadOut.value = longCount(FKeyPad.ReadOut.value,"-1","*");
}

function goReturn()
{
top.returnValue = FKeyPad.ReadOut.value;
self.close();
}
function CheckOut()
{
var keyCode = window.event.keyCode;
if (keyCode>=48 && keyCode<=57)
{
if (FlagNewNum)
{
FKeyPad.ReadOut.value = "";
FlagNewNum = false;
}
return true;
}else if (keyCode==43 || keyCode==45 || keyCode==42 || keyCode==47 || keyCode==61) {
Operation(String.fromCharCode(keyCode));
}else if (keyCode==46) {
if (FKeyPad.ReadOut.value.indexOf(".") == -1)
return true;
}else if (keyCode==27) goReturn();
window.event.returnValue = false;
return false;
}
// End -->
</SCRIPT>
</body>
</html>

『柒』 JS實現簡單的計算器功能

<!doctypehtml>
<html>
<head>
<metacharset="utf-8">
<title>無標題文檔</title>
<style>
table{
border-collapse:separate;
border-spacing:8px;
width:800px;
}
table,td{
border:1pxdashedblack;
padding:1px;
}
</style>
<scriptlanguage="javascript">
functionadd()
{
varn1=parseInt(document.getElementById('n1').value);
varn2=parseInt(document.getElementById('n2').value);
varn3=n1+n2;
document.getElementById('n3').value=n3;
}
functionminx()
{
varn1=parseInt(document.getElementById('n1').value);
varn2=parseInt(document.getElementById('n2').value);
varn3=n1-n2;
document.getElementById('n3').value=n3;
}
functionplus()
{
varn1=parseInt(document.getElementById('n1').value);
varn2=parseInt(document.getElementById('n2').value);
varn3=n1*n2;
document.getElementById('n3').value=n3;
}
functiondivd()
{
varn1=parseInt(document.getElementById('n1').value);
varn2=parseInt(document.getElementById('n2').value);
varn3=n1/n2;
document.getElementById('n3').value=n3;
}
</script>
</head>
<body>
<table>
<tr>
<tdcolspan="4">
第一個數:
<inputtype="text"id="n1"size="4"maxlength="10">
</td>
<tdcolspan="4">
第二個數:
<inputtype="text"id="n2"size="4"maxlength="10">
</td>
<tdcolspan="4">
結果:
<inputtype="text"id="n3"size="4"maxlength="10">
</td>
</tr>
<tr>
<tdcolspan="3">
<inputtype="button"name="button"id="button1"value="+"onclick="add()">
</td>
<tdcolspan="3">
<inputtype="button"name="button"id="button2"value="-"onclick="minx()">
</td>
<tdcolspan="3">
<inputtype="button"name="button"id="button3"value="*"onclick="plus()">
</td>
<tdcolspan="3">
<inputtype="button"name="button"id="button4"value="/"onclick="divd()">
</td>
</tr>
</table>
</body>
</html>

以上代碼是我修改後的,你的代碼有幾個問題:

  1. 沒有方法 document.getElementsByld,應該是document.getElementById,注意:你用的是'L',應該是'哎'。同時html中input的name="n1",name="n2",name="n3"修改為id="n1",id="n2",id="n3"。

  2. var n2=parseInt(document.getElementsByld('n2').value); 你每次獲取n2的值的時候用的是中文的前括弧,js裡面是不允許的。

  3. document.getElementsByld('n3').value)=n3; 在個n3賦值的時候,前括弧也是中文的,value後面多了一個後括弧。

『捌』 如何使用javascript編寫一個計算器

首先,由於JS的存在數值的精度誤差問題:

0.1+0.2 //0.30000000000000004
0.3-0.1 //0.19999999999999998

所以在編寫計算器是應首先解決計算精度問題,以下四個代碼段分別是js中精確的加減乘除運算函數

//浮點數加法運算
function floatAdd(arg1,arg2){
var r1,r2,m;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
return (arg1*m+arg2*m)/m
}

//浮點數減法運算
function floatSub(arg1,arg2){
var r1,r2,m,n;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
//動態控制精度長度
n=(r1>=r2)?r1:r2;
return ((arg1*m-arg2*m)/m).toFixed(n);
}

//浮點數乘法運算
function floatMul(arg1,arg2){
var m=0,s1=arg1.toString(),s2=arg2.toString();
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}

//浮點數除法運算
function floatDiv(arg1,arg2) {
var t1 = 0, t2 = 0, r1, r2;
try {t1 = arg1.toString().split(".")[1].length} catch (e) {}
try {t2 = arg2.toString().split(".")[1].length} catch (e) {}
with (Math) {
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * pow(10, t2 - t1);
}
}

以下是詳細的計算器代碼:
HTML5

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>簡單計算器</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="calculator">

<div id="calculator_container">
<h3>計算器</h3>
<table id="calculator_table">
<tbody>
<tr>
<td colspan="5">
<input type="text" id="resultIpt" readonly="readonly" value="" size="17" maxlength="17" style="width:294px;color: black">
</td>
</tr>
<tr>
<td><input type="button" value="←" class="btn_color1 btn_operation"></td>
<td><input type="button" value="全清" class="btn_color1 btn_operation"></td>
<td><input type="button" value="清屏" class="btn_color1"></td>
<td><input type="button" value="﹢/﹣" class="btn_color2 btn_operation"></td>
<td><input type="button" value="1/×" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="7" class="btn_color3 btn_number"></td>
<td><input type="button" value="8" class="btn_color3 btn_number"></td>
<td><input type="button" value="9" class="btn_color3 btn_number"></td>
<td><input type="button" value="÷" class="btn_color4 btn_operation"></td>
<td><input type="button" value="%" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="4" class="btn_color3 btn_number"></td>
<td><input type="button" value="5" class="btn_color3 btn_number"></td>
<td><input type="button" value="6" class="btn_color3 btn_number"></td>
<td><input type="button" value="×" class="btn_color4 btn_operation"></td>
<td><input type="button" value="√" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="1" class="btn_color3 btn_number"></td>
<td><input type="button" value="2" class="btn_color3 btn_number"></td>
<td><input type="button" value="3" class="btn_color3 btn_number"></td>
<td><input type="button" value="-" class="btn_color4 btn_operation"></td>
<td rowspan="2">
<input type="button" value="=" class="btn_color2" style="height: 82px" id="simpleEqu">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="0" class="btn_color3 btn_number" style="width:112px">
</td>
<td><input type="button" value="." class="btn_color3 btn_number" ></td>
<td><input type="button" value="+" class="btn_color4 btn_operation"></td>
</tr>
</tbody>
</table>

</div>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>


CSS3

* {
margin: 0;
padding: 0;
}
#calculator{
position: relative;
margin: 50px auto;
width: 350px;
height: 400px;
border: 1px solid gray;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 2px 2px 4px gray;
-moz-box-shadow: 2px 2px 4px gray;
box-shadow: 2px 2px 4px gray;
behavior:url("ie-css3.htc"); /*IE8-*/
}
#calculator_table{
position: relative;
margin: 10px auto;
border-collapse:separate;
border-spacing:10px 20px;
}
h3{
position: relative;
width: 60px;
height: 30px;
margin: 0 auto;
}
#calculator_table td{
width: 50px;
height: 30px;
border: 1px solid gray;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
behavior:url("ie-css3.htc"); /*IE8-*/
}
#calculator_table td input{
font-size: 16px;
border: none;
width: 50px;
height: 30px;
color: white;
}
input.btn_color1{
background-color: orange;
}
input.btn_color2{
background-color: #133645;
}
input.btn_color3{
background-color: #59807d;
}
input.btn_color4{
background-color: seagreen;
}
input:active{
-webkit-box-shadow: 3px 3px 3px gray;
-moz-box-shadow: 3px 3px 3px gray;
box-shadow: 3px 3px 3px gray;
behavior:url("ie-css3.htc"); /*IE8-*/
}

JS

window.onload=function() {
var resultIpt = document.getElementById("resultIpt"); //獲取輸出文本框
var btns_number = document.getElementsByClassName("btn_number"); //獲取數字輸入按鈕
var btns_operation = document.getElementsByClassName("btn_operation"); //獲取操作按鈕
var simpleEqu = document.getElementById("simpleEqu"); //獲取"="按鈕
var temp = "";
var num1= 0,num2=0;
//獲取第一個數
for(var i=0;i<btns_number.length;i++){
btns_number[i].onclick=function (){
temp += this.value;
resultIpt.value = temp;
};
}
//對獲取到的數進行操作
for(var j=0;j<btns_operation.length;j++) {
btns_operation[j].onclick = function () {
num1=parseFloat(resultIpt.value);
oper = this.value;
if(oper=="1/×"){
num1 = Math.pow(num1,-1); //取倒數
resultIpt.value = num1.toString();
}else if(oper=="﹢/﹣"){ //取相反數
num1 = -num1;
resultIpt.value = num1.toString();
}else if(oper=="√"){ //取平方根
num1 =Math.sqrt(num1);
resultIpt.value = num1.toString();
}else if(oper=="←"){ //刪除個位
resultIpt.value = resultIpt.value.substring(0, resultIpt.value.length - 1);

}else if(oper=="全清"){ //清除數字
resultIpt.value = "";
}
else{ //oper=="+" "-" "×" "÷" "%"時,繼續輸入第二數字
temp = "";
resultIpt.value = temp;
}
}
}
//輸出結果
simpleEqu.onclick=function(){
num2=parseFloat(temp); //取得第二個數字
calculate(num1, num2, oper);
resultIpt.value = result.toString();
}
};

//定義一個計算函數
function calculate(num1, num2, oper) {
switch (oper) {
case "+":
result=floatAdd(num1, num2); //求和
break;
case "-":
result=floatSub(num1, num2); //求差
break;
case "×":
result=floatMul(num1, num2); //求積
break;
case "÷":
result=floatDiv(num1, num2); //求商
break;
case "%":
result=num1%num2; //求余數
break;
}
}

//精確計算
//浮點數加法運算
function floatAdd(arg1,arg2){
var r1,r2,m;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
return (arg1*m+arg2*m)/m
}
//浮點數減法運算
function floatSub(arg1,arg2){
var r1,r2,m,n;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
//動態控制精度長度
n=(r1>=r2)?r1:r2;
return ((arg1*m-arg2*m)/m).toFixed(n);
}
//浮點數乘法運算
function floatMul(arg1,arg2){
var m=0,s1=arg1.toString(),s2=arg2.toString();
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//浮點數除法運算
function floatDiv(arg1,arg2) {
var t1 = 0, t2 = 0, r1, r2;
try {t1 = arg1.toString().split(".")[1].length} catch (e) {}
try {t2 = arg2.toString().split(".")[1].length} catch (e) {}
with (Math) {
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * pow(10, t2 - t1);
}
}

『玖』 js簡易計算器怎麼做必須要用這兩個怎麼辦

也不清楚您 Count 方法具體作用,按自己想法做。

這是 html

<divclass="calculator">
<inputtype="text"value=""id="data">
<br/>
<inputtype="button"value="0"onclick="set('0')">
<inputtype="button"value="1"onclick="set('1')">
<inputtype="button"value="2"onclick="set('2')">
<inputtype="button"value="3"onclick="set('3')">
<br/>
<inputtype="button"value="4"onclick="set('4')">
<inputtype="button"value="5"onclick="set('5')">
<inputtype="button"value="6"onclick="set('6')">
<inputtype="button"value="7"onclick="set('7')">
<br/>
<inputtype="button"value="8"onclick="set('8')">
<inputtype="button"value="9"onclick="set('9')">
<inputtype="button"value="+"onclick="set('+')">
<inputtype="button"value="-"onclick="set('-')">
<br/>
<inputtype="button"value="*"onclick="set('*')">
<inputtype="button"value="/"onclick="set('/')">
<inputtype="button"value="CE"onclick="set('CE')">
<inputtype="button"value="="onclick="Count('=')">
<inputtype="button"value="重置"onclick="set('reset')">
</div>

這是 js

letsetEqual=false;
functionset(item){
letvalue=document.getElementById('data').value;
//重置按鈕
if(item==='reset'){
setEqual=false;
document.getElementById('data').value='';
return;
}
//刪除上一次輸入若上一次按'=',則重置
if(item==='CE'){
if(!setEqual){
document.getElementById('data').value=value.substring(0,value.length-1);
}else{
setEqual=false;
document.getElementById('data').value=''
}
return;
}
//上次輸入'=',重置再輸入
if(setEqual){
setEqual=false;
document.getElementById('data').value=item;
return;
}
//最後一位為計算符號,且輸入計算符號,刪除上一個符號;首位是*/刪除再重新輸入
if(/[-+*/]$/.test(item)&&/[-+*/]$/.test(value)||/^[*/]$/.test(value)){
value=value.substring(0,value.length-1);
}
//首位為0且輸入數字,刪除0,再輸入
if(value==='0'&&/d/.test(item)){
value=value.substring(0,value.length-1);
}
document.getElementById('data').value=value+item;
}

functionCount(item){
if(setEqual){
document.getElementById('data').value='';
returnfalse;
}
setEqual=true;
letvalue=document.getElementById('data').value;
try{
document.getElementById('data').value=value+item+eval(value);
}catch(e){
console.log(e);
alert('輸入有誤');
document.getElementById('data').value='';
}

}
閱讀全文

與js製作簡易計算器實例相關的資料

熱點內容
蘋果6p微信發送語音會自己中斷 瀏覽:644
win10拷貝文件到u盤速度慢 瀏覽:396
怎麼把ps源文件字體改清楚 瀏覽:440
u盤如何恢復win10系統下載 瀏覽:153
完美世界100級升級攻略 瀏覽:67
安卓手機去除廣告軟體 瀏覽:529
水果禮品卡網站有哪些 瀏覽:272
愛譜數據線纜多少錢 瀏覽:165
word轉換成圖片格式 瀏覽:182
移動數據收費標準是多少 瀏覽:952
me525微信451去升級版 瀏覽:152
如何把壓縮文件變成永久文件 瀏覽:828
數據分片最大值多少 瀏覽:598
會玩app開完小號如何找回大號 瀏覽:939
html顯示flash代碼 瀏覽:651
while語句java 瀏覽:376
iphone鉻黃ps 瀏覽:529
linux掛載到已有分區 瀏覽:327
飛行員報告的數據都有哪些 瀏覽:482
騰訊視頻app怎麼傳視頻 瀏覽:125

友情鏈接