```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>简单计算器</title>
</head>
<body>
<div>
  <input type="text" size="5" id="num1" value=""  onchange="fun(this.id)"/>
  <select id="ysf">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
    <option value="%">%</option>
  </select>
  <input type="text" size="5" id="num2" value="" onchange="fun(this.id)"/>
  <input type="button" value="计算" id="btn"/>
</div>
<p id="res"></p>
<script>
    // 设置两个输入框只能输入数字
        function fun(id) {
            var patrn = /^\d+(.\d+)?$/;//正则表达式匹配规则
            var num = document.getElementById(id);
            if (!patrn.exec(num.value)) {
                alert(“只能输入数字!”);
                num.value = “”;
            }
        }
  //获取按钮注册事件
  document.getElementById(‘btn’).onclick=function(){
    var num1 = document.getElementById(‘num1’);
    var num2 = document.getElementById(‘num2’);
    var ysf = document.getElementById(‘ysf’);
    var res = document.getElementById(‘res’);
    switch (ysf.value){
        case “+”:
            res = parseFloat(num1) + parseFloat(num2.value);
            break;
        case “-“:
            res = parseFloat(num1.value) - parseFloat(num2.value);
            break;
        case ““:
            res = parseFloat(num1.value)  parseFloat(num2.value);
            break;
        case “/“:
            res = parseFloat(num1.value) / parseFloat(num2.value);
            break;
        case “%”:
            res = parseFloat(num1.value) % parseFloat(num2.value);
            break;
    }
      res.value = res
     document.getElementById(‘res’).innerHTML=num1.value +ysf.value+num2.value+”=”+res;
  };
</script>
</body>
</html>
```
 
                 
                        
                    Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号