<p>以下是使用 HTML5 和 JavaScript 编写的计算器示例:</p>
<!DOCTYPE html>
<html>
<head>
	<title>计算器</title>
	<style>
		.container{
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-top: 50px;
		}
		.input-field {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 20px;
		}
		input[type="text"] {
			width: 250px;
			height: 40px;
			font-size: 24px;
			text-align: right;
			padding: 5px;
			border-radius: 5px;
			border: none;
			box-shadow: 0px 0px 5px grey;
			margin-right: 10px;
		}
		input[type="button"] {
			width: 50px;
			height: 40px;
			font-size: 24px;
			border-radius: 5px;
			border: none;
			box-shadow: 0px 0px 5px grey;
			cursor: pointer;
		}
		input[type="button"]:hover {
			background-color: #eee;
		}
	</style>
</head>
<body>
	<div class='container'>
		<div class='input-field'>
			<input type='text' id='result' disabled>
		</div>
		<div class='input-field'>
			<input type='button' value='7' onclick='addToResult('7')'>
			<input type='button' value='8' onclick='addToResult('8')'>
			<input type='button' value='9' onclick='addToResult('9')'>
			<input type='button' value='/' onclick='addToResult('/')'>
			<input type='button' value='C' onclick='clearResult()'>
		</div>
		<div class='input-field'>
			<input type='button' value='4' onclick='addToResult('4')'>
			<input type='button' value='5' onclick='addToResult('5')'>
			<input type='button' value='6' onclick='addToResult('6')'>
			<input type='button' value='*' onclick='addToResult('*')'>
			<input type='button' value='CE' onclick='clearLastEntry()'>
		</div>
		<div class='input-field'>
			<input type='button' value='1' onclick='addToResult('1')'>
			<input type='button' value='2' onclick='addToResult('2')'>
			<input type='button' value='3' onclick='addToResult('3')'>
			<input type='button' value='-' onclick='addToResult('-')'>
			<input type='button' value='.' onclick='addToResult('.')'>
		</div>
		<div class='input-field'>
			<input type='button' value='0' onclick='addToResult('0')'>
			<input type='button' value='+' onclick='addToResult('+')'>
			<input type='button' value='=' onclick='calculate()'>
		</div>
	</div>
<pre><code>&lt;script&gt;
	function addToResult(value) {
		document.getElementById(&quot;result&quot;).value += value;
	}

	function clearResult() {
		document.getElementById(&quot;result&quot;).value = '';
	}

	function clearLastEntry() {
		var result = document.getElementById(&quot;result&quot;).value;
		document.getElementById(&quot;result&quot;).value = result.substring(0, result.length - 1);
	}

	function calculate() {
		var result = document.getElementById(&quot;result&quot;).value;
		if (result) {
			document.getElementById(&quot;result&quot;).value = eval(result);
		}
	}
&lt;/script&gt;
</code></pre>
</body>
</html>
HTML5 计算器示例代码 - 用 JavaScript 实现简单的计算功能

原文地址: https://www.cveoy.top/t/topic/msBU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录