HTML
首先我们在网页上放置一个输入框及多个计算器按钮。
<div> <input type="text" value="0" size="21" maxlength="21" readonly="readonly" /> <div> <div> C</div> <div> +/-</div> <div> %</div> <div> ←</div> <div> 7</div> <div> 8</div> <div> 9</div> <div> +</div> <div> -</div> <div> 4</div> <div> 5</div> <div> 6</div> <div> ×</div> <div> ÷</div> <div> 1</div> <div> 2</div> <div> 3</div> <div> ײ</div> <div> √</div> <div> 0</div> <div> .</div> <div> =</div> </div> </div>
js
根据操作类型作相应操作:
function operator(type) { switch (type) { case "clear": input.value = "0"; _string.length = 0; /*document.getElementById("ccc").innerHTML=""; for(i=0;i<_string.length;i++) { document.getElementById("ccc").innerHTML+=_string[i]+" " }*/ break; case "backspace": if (checknum(input.value) != 0) { input.value = input.value.replace(/.$/, ''); if (input.value == "") { input.value = "0"; } } break; case "opposite": if (checknum(input.value) != 0) { input.value = -input.value; } break; case "percent": if (checknum(input.value) != 0) { input.value = input.value / 100; } break; case "pow": if (checknum(input.value) != 0) { input.value = Math.pow(input.value, 2); } break; case "sqrt": if (checknum(input.value) != 0) { input.value = Math.sqrt(input.value); } break; case "plus": if (checknum(input.value) != 0) { _string.push(input.value); _type = "plus"input.value = "+"; input.name = "type"; } break; case "minus": if (checknum(input.value) != 0) { _string.push(input.value); _type = "minus"input.value = "-"; input.name = "type"; } break; case "multiply": if (checknum(input.value) != 0) { _string.push(input.value); _type = "multiply"input.value = "×"; input.name = "type"; } break; case "divide": if (checknum(input.value) != 0) { _string.push(input.value); _type = "divide"input.value = "÷"; input.name = "type"; } break; case "result": if (checknum(input.value) != 0) { _string.push(input.value); if (parseInt(_string.length) % 2 != 0) { _string.push(_string[_string.length - 2]) } if (_type == "plus") { input.value = parseFloat(result(_string)[0]) + parseFloat(result(_string)[1]); input.name = "type" } else if (_type == "minus") { input.value = parseFloat(result(_string)[0]) - parseFloat(result(_string)[1]); input.name = "type" } else if (_type == "multiply") { input.value = parseFloat(result(_string)[0]) * parseFloat(result(_string)[1]); input.name = "type" } else if (_type == "divide") { input.value = parseFloat(result(_string)[0]) / parseFloat(result(_string)[1]); input.name = "type" } break; } } }