为了实现一个精美的计算器网页,我们可以使用HTML和JavaScript来构建界面和处理计算逻辑。下面是一个简单的示例:
1. 创建HTML结构:
<!DOCTYPE html>
<html>
<head>
<title>精美计算器</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="result" readonly>
<div class="buttons">
<button onclick="clearResult()">C</button>
<button onclick="appendToResult('/')">/</button>
<button onclick="appendToResult('*')">*</button>
<button onclick="appendToResult('7')">7</button>
<button onclick="appendToResult('8')">8</button>
<button onclick="appendToResult('9')">9</button>
<button onclick="appendToResult('-')">-</button>
<button onclick="appendToResult('4')">4</button>
<button onclick="appendToResult('5')">5</button>
<button onclick="appendToResult('6')">6</button>
<button onclick="appendToResult('+')">+</button>
<button onclick="appendToResult('1')">1</button>
<button onclick="appendToResult('2')">2</button>
<button onclick="appendToResult('3')">3</button>
<button onclick="calculate()">=</button>
<button onclick="appendToResult('0')">0</button>
<button onclick="appendToResult('.')">.</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. 创建CSS样式(styles.css):
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
background-color: #f0f0f0;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 300px;
}
#result {
font-size: 24px;
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
}
button {
font-size: 20px;
padding: 10px;
border: none;
background-color: #e0e0e0;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s ease;
}
button:hover {
background-color: #d0d0d0;
}
3. 创建JavaScript脚本(script.js):
let result = document.getElementById("result");
function appendToResult(value) {
result.value += value;
}
function clearResult() {
result.value = "";
}
function calculate() {
try {
result.value = eval(result.value);
} catch (error) {
result.value = "Error";
}
}
该计算器网页使用HTML定义了页面结构,CSS样式使其具有精美的外观,而JavaScript脚本实现了计算器的逻辑。用户可以通过按钮输入数字和操作符,并通过“=”按钮来进行计算,计算结果会显示在文本框中。