使用 JavaScript 构建计算器应用程序

要使用 JavaScript 构建一个简单的计算器,我们需要处理基本的算术运算,例如加法、减法、乘法和除法。JavaScript 通常与 HTML 和 CSS 结合使用,以创建交互式的基于 Web 的计算器。

我们将创建什么

我们将构建一个简单且功能齐全的计算器,它将具备以下特点:

  • 简洁且响应式的设计。
  • 用于每个数字和运算的按钮。
  • 显示当前输入和结果的显示区域。
  • 用于清除屏幕的按钮。

项目预览

!Screenshot-2025-03-08-152454JavaScript Calculator App

计算器 – HTML 结构与 CSS 样式



    
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f2f2f2;
            margin: 0;
        }

        .calculator {
            width: 300px;
            background-color: #fff;
            border-radius: 15px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .display {
            width: 100%;
            height: 50px;
            text-align: right;
            font-size: 1.5rem;
            padding: 10px;
            margin-bottom: 20px;
            border: none;
            background-color: #ffeb3b;
            border-radius: 8px;
            color: #333;
        }

        .buttons {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }

        .button {
            background-color: #03a9f4;
            border: none;
            font-size: 1.5rem;
            padding: 20px;
            cursor: pointer;
            border-radius: 10px;
            transition: background-color 0.3s, transform 0.2s;
            color: white;
        }

        .button:hover {
            background-color: #0288d1;
            transform: scale(1.1);
        }

        .button:active {
            transform: scale(0.95);
        }

        .button.clear {
            background-color: #ff5722;
        }

        .button.clear:hover {
            background-color: #e64a19;
        }

        .button.equal {
            background-color: #8bc34a;
        }

        .button.equal:hover {
            background-color: #689f38;
        }

        .button.operator {
            background-color: #ff9800;
        }

        .button.operator:hover {
            background-color: #f57c00;
        }
    

    

在此示例中:

  • 代码定义了一个简单的计算器界面的 HTML 结构,包含一个用于显示的输入字段以及一组用于数字、运算符和操作的按钮。
  • INLINECODE4d572b87 的 INLINECODE8554b3f4 元素充当计算器的显示区域,用户可以在其中查看结果。它被设置为禁用状态,这意味着用户无法直接在其中输入;它仅用于显示输出。
  • 计算器的按钮位于
    内部。有用于数字 (0-9)、算术运算符 (+, -, *, /) 的按钮,以及像 C (清除) 和 = (等于) 这样的特殊按钮。
  • 按钮按行分组,例如数字在一行,运算符在另一行,等号和清除按钮位于它们各自的位置,以便于视觉组织。
  • Body 样式: 使用灵活布局和浅灰色背景使内容居中。
  • 计算器容器:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/43885.html
点赞
0.00 平均评分 (0% 分数) - 0