用HTML生成一个计算器。可以进行四则运算。乘方。三角函数。等。
以下是一个简单的HTML计算器示例,可以进行四则运算、乘方和三角函数的计算:
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
<style>
.calculator {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="text"], input[type="button"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="result" readonly>
<input type="button" value="1" onclick="appendToResult('1')">
<input type="button" value="2" onclick="appendToResult('2')">
<input type="button" value="3" onclick="appendToResult('3')">
<input type="button" value="+" onclick="appendToResult('+')">
<input type="button" value="4" onclick="appendToResult('4')">
<input type="button" value="5" onclick="appendToResult('5')">
<input type="button" value="6" onclick="appendToResult('6')">
<input type="button" value="-" onclick="appendToResult('-')">
<input type="button" value="7" onclick="appendToResult('7')">
<input type="button" value="8" onclick="appendToResult('8')">
<input type="button" value="9" onclick="appendToResult('9')">
<input type="button" value="*" onclick="appendToResult('*')">
<input type="button" value="0" onclick="appendToResult('0')">
<input type="button" value="." onclick="appendToResult('.')">
<input type="button" value="=" onclick="calculateResult()">
<input type="button" value="/" onclick="appendToResult('/')">
<input type="button" value="sin" onclick="calculateSin()">
<input type="button" value="cos" onclick="calculateCos()">
<input type="button" value="tan" onclick="calculateTan()">
<input type="button" value="^" onclick="appendToResult('**')">
<input type="button" value="C" onclick="clearResult()">
</div>
<script>
function appendToResult(value) {
document.getElementById('result').value += value;
}
function calculateResult() {
var result = eval(document.getElementById('result').value);
document.getElementById('result').value = result;
}
function calculateSin() {
var result = Math.sin(eval(document.getElementById('result').value));
document.getElementById('result').value = result;
}
function calculateCos() {
var result = Math.cos(eval(document.getElementById('result').value));
document.getElementById('result').value = result;
}
function calculateTan() {
var result = Math.tan(eval(document.getElementById('result').value));
document.getElementById('result').value = result;
}
function clearResult() {
document.getElementById('result').value = '';
}
</script>
</body>
</html>
该计算器使用了HTML和JavaScript,其中appendToResult()函数用于将按钮的值追加到输入框中,calculateResult()函数用于计算结果并显示在输入框中,calculateSin()、calculateCos()和calculateTan()函数用于计算三角函数的结果,clearResult()函数用于清除输入框中的内容
原文地址: http://www.cveoy.top/t/topic/hLhS 著作权归作者所有。请勿转载和采集!