<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>迷你计算器</title>
<style type="text/css">
.box {
width: 650px;
height: 200px;
text-align: center;
background-color: #efefef;
color: #636363;
margin: auto;
/*margin: 20px auto;*/
border-radius: 15px;
box-shadow: 2px 2px 2px #999;
}
table {
margin: auto;
}
.box table td {
width: 100px;
height: 30px;
padding: 5px 10px;
}
input select {
width: 100%;
height: 100%;
border: none;
text-align: center;
}
.box table button {
width: 100%;
height: 100%;
border: none;
color: white;
text-align: center;
background-color: #555;
}
.box table button:hover {
background-color: coral;
font-size: 1.1em;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<form>
<caption><h2>迷你计算器</h2></caption>
<table>
<tr>
<td><input type="text" name="data1" placeholder="操作数1"></td>
<td>
<select name="option">
<option value="null">请选择操作</option>
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
</td>
<td><input type="text" name="data2" placeholder="操作数2"></td>
<td><button type="button">计算</button></td>
</tr>
<tr>
<td colspan="2" align="right"><h3>结果:</h3></td>
<td colspan="2" align="left"><h3 id="result"></h3></td>
</tr>
</table>
</form>
</div>
<script type="text/javascript">
// 获取操作数,按钮与结果占位符
var data1 = document.getElementsByName('data1') [0]
var data2 = document.getElementsByName('data2') [0]
var opt = document.getElementsByName('option') [0]
var btn = document.getElementsByTagName('button') [0]
var result = document.getElementById('result')
btn.onclick = function(){
if (data1.value.length == 0) {
alert('第一个操作数不能为空')
data1.focus()
return false
} else if (isNaN(data1.value)) {
alert('第一个操作数必须是数字')
data1.focus()
return false
} else if (data2.value.length == 0) {
alert('第二个操作数不能为空')
data2.focus()
return false
} else if (isNaN(data2.value)) {
alert('第二个操作数必须是数字')
data2.focus()
return false
} else {
var data11 = parseFloat(data1.value)
var data12 = parseFloat(data2.value)
}
var option = opt.value
var temp = 0
var flag = ''
switch (option) {
case 'null':
alert('请选择操作类型')
opt.focus()
return false
case 'add':
flag = '+'
temp = data11 + data12
break
case 'sub':
flag = '-'
temp = data11 - data12
break
case 'mul':
flag = '*'
temp = data11 * data12
break
case 'div':
flag = '/'
if (data12 == 0) {
alert('除数不能为0,请重新输入')
data2.focus()
return false
} else {
temp = data11 / data12
}
break
}
result.innerHTML = temp;
}
</script>
</body>
</html>