JS_实现简单计算器

超级超级简单的计算器一个。

 


 

HTML代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>简易计算器</title>
        <link rel="stylesheet" href="calculator.css">
        <script charset="utf-8" type="text/javascript" src="calculator.js"></script>
    </head>
    <body>
        <h3 align="center">简易计算器</h3>
        <div id="divshow">
            <!--显示文本框,不允许键盘输入-->
            <input type="text" id="show_text"  readonly="readonly">
            <br>
            <!--按钮-->
            <input type="button" value="1" onclick="my_sum(this)">
            <input type="button" value="2" onclick="my_sum(this)">
            <input type="button" value="3" onclick="my_sum(this)">
            <input type="button" value="+" onclick="my_sum(this)">
            <br>
            <input type="button" value="4" onclick="my_sum(this)">
            <input type="button" value="5" onclick="my_sum(this)">
            <input type="button" value="6" onclick="my_sum(this)">
            <input type="button" value="-" onclick="my_sum(this)">
            <br>
            <input type="button" value="7" onclick="my_sum(this)">
            <input type="button" value="8" onclick="my_sum(this)">
            <input type="button" value="9" onclick="my_sum(this)">
            <input type="button" value="/" onclick="my_sum(this)">
            <br>
            <input type="button" value="0" onclick="my_sum(this)">
            <input type="button" value="clear" onclick="my_sum(this)">
            <input type="button" value="=" onclick="my_sum(this)">
            <input type="button" value="%" onclick="my_sum(this)">
        </div>
    </body>
</html>

css代码:

/*整个计算器盒子的样式*/
div{
    width: 300px;
    height: 300px;
    border: solid 1px;
    border-radius: 15px;
    margin:10px auto;
    background-color: aqua;
}
/*文本框样式*/
input[type="text"]{
    width: 270px;
    height: 40px;
    padding: 0;
    border: 0ch;
    margin-top: 20px;
    margin-bottom: 40px;
    margin-left: 15px;
    margin-right: 15px;
    font-size:20px;
    font-weight:bold;
}
/*按钮的样式*/
input[type="button"]{
    width: 60px;
    margin-bottom: 5px;
    margin-left: 9px;
    font-size: 20px;
    font-weight:bold;
}

js代码:

function my_sum(numb) {
    //获取按钮的值
    var my_number = numb.value;
    //判断
    switch(my_number) {
        //按下clear按钮,清除文本框内容
        case "clear":
            document.getElementById("show_text").value="";
            break;
        //按下=号,进行运算,显示结果
        case "=":
            //eval函数:把字符串作为代码进行执行。
            document.getElementById("show_text").value=eval(document.getElementById("show_text").value);
            break;
        //按下数字键或运算符,显示在文本框
        default:
            document.getElementById("show_text").value+=my_number;
    }
}

运行结果:

 

posted @ 2023-01-13 15:30  在博客做笔记的路人甲  阅读(384)  评论(0编辑  收藏  举报