Javascriptで簡易電卓を作る方法をまとめました。
簡易電卓
Javascriptで簡単な電卓を作ってみました。
コードを動的に実行できる「eval関数」を使用することで、10行程度で作成できます。
実行例
サンプルコード
サンプルプログラムのソースコードです。
Jacapre
function calc(cmd) {
if (cmd == "=") {
document.form.text.value = eval(document.form.text.value);
} else if (cmd == "C") {
document.form.text.value = "";
} else {
document.form.text.value += cmd;
}
}
HTML
<!DOCtype html>
<html>
<head>
<meta charset="utf-8">
<title>簡易電卓</title>
<pre title="main.js"></pre>
<link rel='stylesheet' href='main.css' type='text/css' />
</head>
<body>
<form name="form" id="calcForm">
<table id="calcTable">
<tr>
<td colspan="3"><input type="text" name="text" value="0"></td>
<td><input type="button" value="C" onClick="calc('C')"></td>
</tr>
<tr>
<td><input type="button" value="7" onClick="calc('7')"></td>
<td><input type="button" value="8" onClick="calc('8')"></td>
<td><input type="button" value="9" onClick="calc('9')"></td>
<td><input type="button" value="/" onClick="calc('/')"></td>
</tr>
<tr>
<td><input type="button" value="4" onClick="calc('4')"></td>
<td><input type="button" value="5" onClick="calc('5')"></td>
<td><input type="button" value="6" onClick="calc('6')"></td>
<td><input type="button" value="✕" onClick="calc('*')"></td>
</tr>
<tr>
<td><input type="button" value="1" onClick="calc('1')"></td>
<td><input type="button" value="2" onClick="calc('2')"></td>
<td><input type="button" value="3" onClick="calc('3')"></td>
<td><input type="button" value="-" onClick="calc('-')"></td>
</tr>
<tr>
<td><input type="button" value="0" onClick="calc('0')"></td>
<td><input type="button" value="." onClick="calc('.')"></td>
<td><input type="button" value="+" onClick="calc('+')"></td>
<td><input type="button" value="=" onClick="calc('=')"></td>
</tr>
</table>
</form>
</body>
</html>
CSS
#calcTable{
text-align:center;
color:#fff;
}
| – | 関連記事 |
|---|---|
| 1 | Javascript入門 |


コメント