基于JavaScript实现简易计算器

编辑: admin 分类: javascript 发布时间: 2022-01-05 来源:互联网

本文实例为大家分享了JavaScript实现简易计算器的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算器</title>
    <style>
        .op {
            margin: 50px auto;
            width: 300px;
            height: 300px;
            border: 1px solid orange;
            background-color: lightskyblue;
            border-radius: 50px;
        }

        input {
            width: 210px;
            height: 30px;
            border-radius: 5px;
        }

        button {
            width: 30px;
            height: 30px;
            border-radius: 10px;
        }
    </style>
</head>
<body>
<div class="op">
    <h2 align="center">计算器</h2>
    <form name="calculator">
        <table align="center">
            <tr>
                <td>num1:</td>
                <td><input type="text" name="num1"></td>
            </tr>
            <tr>
                <td>num2:</td>
                <td><input type="text"【转自:http://www.1234xp.com/lg.html转载】 name="num2"></td>
            </tr>
            <tr>
                <td colspan="2">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <button type="button">+</button>
                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <button type="button">-</button>
                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <button type="button">*</button>
                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <button type="button">/</button>
                </td>
            </tr>
            <tr>
                <td>结果:</td>
                <td><input type="text" name="result" disabled></td>
            </tr>
        </table>
    </form>
</div>
<script>
    //得到标签名下的所有元素对象,返回一个数组
    let buttonArr = document.getElementsByTagName("button");
    for (let but of buttonArr) {
        but.addEventListener('click', function () {
            let operator = this.innerHTML;
            count(operator);
        });
    }

    function count(operator) {
        //得到form为calculator中name为num1的输入值
        let num1 = parseFloat(document.calculator.num1.value);
        let num2 = parseFloat(document.calculator.num2.value);
        let result = '';
        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                if (num2 == 0) {
                    alert("除数不能为零");
                    return;
                }
                result = num1 / num2;
                break;
        }
//将结果赋值于属性名name为result的input框
        document.calculator.result.value = result;
    }
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持海外IDC网。

【文章由http://www.yidunidc.com/lg.html 欢迎留下您的宝贵建议】