最终效果:

html结构:
<style>
input[name="num1"],input[name="num2"]{
width: 50px;
}
input[name="result"]{
border:none;
border-bottom:1px solid #ccc;
width: 150px;
background-color: transparent;
}
*{
margin:5px;
padding:6px;
outline:none;
}
button{
width: 50px;
}
</style>
<input type="number" name="num1">
<select name="operator">
<option value="0">选择运算符</option>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="num2">
<button class="count">=</button>
<input type="number" name="result" disabled>
js逻辑代码
// 获取所有标签
var num1 = document.querySelector('[name="num1"]');
var operator = document.querySelector('[name="operator"]');
var num2 = document.querySelector('[name="num2"]');
var result = document.querySelector('[name="result"]');
var countBtn = document.querySelector('.count');
// 点击等于号
countBtn.onclick = function(){
// 判断运算符
switch(operator.value){
case '+': // 如果运算符是+
// 将两个数字文本框中的值转为数字进行加法运算,结果放在result里面
result.value = +num1.value + +num2.value;
break;
case '-': // 如果运算符是-
// 将两个数字文本框中的值转为数字进行减法运算,结果放在result里面
result.value = +num1.value - +num2.value;
break;
case '*': // 如果运算符是*
// 将两个数字文本框中的值转为数字进行乘法运算,结果放在result里面
result.value = +num1.value * +num2.value;
break;
case '/': // 如果运算符是/
// 将两个数字文本框中的值转为数字进行除法运算,结果放在result里面
result.value = +num1.value / +num2.value;
break;
default: // 如果运算符不是+-*/,就是没有选择
alert("请选择运算符")
}
}
网友评论