搜索
首页web前端前端问答利用jquery实现计算器

计算器是人们日常生活中不可或缺的工具之一,也是Web开发中经常需要实现的功能之一。在本文中,我们将通过利用jQuery库来实现一个简单的计算器,该计算器支持四则运算以及小数运算,并且可以使用键盘输入。

首先,我们需要创建一个HTML页面来承载我们的计算器。HTML结构如下:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery计算器</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="script.js"></script>
</head>
<body>
    <div id="calculator">
        <div class="display">
            <input type="text" id="result" readonly>
        </div>
        <div class="keys">
            <button id="clear">AC</button>
            <button id="sign">+/-</button>
            <button id="percent">%</button>
            <button class="operator" id="divide">/</button>
            <button class="number" id="seven">7</button>
            <button class="number" id="eight">8</button>
            <button class="number" id="nine">9</button>
            <button class="operator" id="multiply">*</button>
            <button class="number" id="four">4</button>
            <button class="number" id="five">5</button>
            <button class="number" id="six">6</button>
            <button class="operator" id="subtract">-</button>
            <button class="number" id="one">1</button>
            <button class="number" id="two">2</button>
            <button class="number" id="three">3</button>
            <button class="operator" id="add">+</button>
            <button class="number" id="zero">0</button>
            <button id="decimal">.</button>
            <button id="equal">=</button>
        </div>
    </div>
</body>
</html>

在这个HTML结构中,我们有一个计算器的容器,其中有两个子元素,一个是显示区域,另一个是按键区域。显示区域使用一个输入框来显示运算结果,而按键区域则包含了数字、运算符等按键,以及其他特殊按键(例如清除、取反、百分比等)。

接下来,我们需要创建一个CSS样式表来美化我们的计算器。CSS样式如下:

body {
    font-family: Arial, sans-serif;
}

#calculator {
    margin: 0 auto;
    width: 310px;
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.display {
    padding: 10px;
    background-color: #f2f2f2;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    text-align: right;
}

#result {
    width: 100%;
    height: 40px;
    font-size: 24px;
    border: 0;
}

.keys {
    display: grid;
    grid-gap: 1px;
    grid-template-columns: repeat(4, 1fr);
    background-color: #efefef;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
}

button {
    width: 100%;
    height: 50px;
    font-size: 20px;
    border: 0;
    color: #fff;
    background-color: #4CAF50;
    cursor: pointer;
    outline: none;
}

button:focus {
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.5);
}

在这个CSS样式中,我们设置了计算器的整体样式,包括边框、阴影、圆角等。为了让键盘按键可以紧密排列,我们使用了CSS网格布局技术,并设置了按键的样式。

接下来,我们需要编写一个JavaScript脚本来处理计算器的逻辑。我们使用jQuery库来简化处理代码的编写和DOM操作。

我们先要全局定义三个变量:

var firstNumber = '';
var operator = '';
var secondNumber = '';

这三个变量将分别存储用户输入的第一个数、运算符和第二个数。

我们使用jQuery的事件处理函数来绑定按键事件。例如,当用户点击数字键时,我们将相应的数字添加到显示区域的输入框中。当用户点击加号和减号键时,我们将相应的运算符存储到变量operator中。当用户点击等号键时,我们根据当前运算符来执行相应的计算并将结果显示到输入框中。具体实现代码如下:

$(document).ready(function() {
    $('.number').click(function() {
        var input = $('#result').val();
        var number = $(this).text();

        // 判断当前输入框中是否已经有小数点
        if (number === '.') {
            if (input.indexOf('.') !== -1) {
                return;
            }
            if (input === '') {
                input = '0';
            }
        }

        input += number;
        $('#result').val(input);
    });

    $('.operator').click(function() {
        firstNumber = $('#result').val();
        operator = $(this).text();
        $('#result').val('');
    });

    $('#equal').click(function() {
        secondNumber = $('#result').val();
        var result = 0;
        var num1 = parseFloat(firstNumber);
        var num2 = parseFloat(secondNumber);

        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num1 / num2;
                break;
        }

        $('#result').val(result);
    });

    $('#clear').click(function() {
        firstNumber = '';
        operator = '';
        secondNumber = '';
        $('#result').val('');
    });

    $('#sign').click(function() {
        var input = $('#result').val();
        var prefix = '';

        if (input.charAt(0) === '-') {
            prefix = input.substr(1);
        } else {
            prefix = '-' + input;
        }

        $('#result').val(prefix);
    });

    $('#percent').click(function() {
        var input = $('#result').val();
        var percent = parseFloat(input) / 100;
        $('#result').val(percent);
    });

    $(document).keydown(function(event) {
        var key = event.key;

        if (!isNaN(key)) {
            $('#' + key).click();
        } else if (key === '+' || key === '-' || key === '*' || key === '/') {
            $('#' + key).click();
        } else if (key === 'Enter') {
            $('#equal').click();
        } else if (key === '.') {
            $('#decimal').click();
        } else if (event.ctrlKey && (key === 'c' || key === 'C')) {
            $('#clear').click();
        }
    });
});

在这个JavaScript脚本中,我们使用了jQuery的事件处理函数click来绑定按键事件。当用户点击数字键时,我们从当前输入框的值中读取已经输入的数字,而如果按键是小数点时,我们需要判断当前输入框中是否已经存在小数点,如果存在则忽略该按键。当用户点击加号或减号时,我们将当前输入框中的数保存到变量firstNumber中,并将运算符保存到变量operator中,并清空当前输入框。当用户点击等号时,我们读取输入框中的值作为第二个数,并根据当前运算符来执行相应的计算,计算结果将显示在输入框中。当用户点击清除键、取反键或百分比键时,我们分别执行相应的操作。当用户按下键盘上的相应按键时,我们模拟相应的按键点击事件。例如,当用户按下数字键时,我们将触发相应数字键的点击事件。

最终,通过HTML页面、CSS样式表和JavaScript脚本的结合,我们实现了一个简单的计算器。用户可以通过鼠标或键盘操作来完成四则运算,并且可以进行小数运算以及其他特殊操作,例如清除、取反和百分比等。本文中的实现只是一个基础的原型,如果你需要实现更丰富的功能,例如支持括号、科学计算等,也可以在此基础上进行扩展。

以上是利用jquery实现计算器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
了解usestate():综合反应国家管理指南了解usestate():综合反应国家管理指南Apr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

使用React的优点是什么?使用React的优点是什么?Apr 25, 2025 am 12:16 AM

ReactispupularduetoItsComponent基于结构结构,虚拟,Richecosystem和declarativentation.1)基于组件的harchitectureallowslowsforreusableuipieces。

在React中调试:识别和解决共同问题在React中调试:识别和解决共同问题Apr 25, 2025 am 12:09 AM

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

反应中的usestate()是什么?反应中的usestate()是什么?Apr 25, 2025 am 12:08 AM

usestate()inrectallowsStateMangementInfunctionalComponents.1)ITSimplifiestTateMempement,MakecodeMoreConcise.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousviousviousVious.3)

usestate()与用户ducer():为您的状态需求选择正确的挂钩usestate()与用户ducer():为您的状态需求选择正确的挂钩Apr 24, 2025 pm 05:13 PM

selectUsestate()forsimple,独立的StateVariables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleUpdatesLikeTogGlikeTogGlikGlingaBglingAboolAboolAupDatingAcount.2)

使用usestate()管理状态:实用教程使用usestate()管理状态:实用教程Apr 24, 2025 pm 05:05 PM

useState优于类组件和其它状态管理方案,因为它简化了状态管理,使代码更清晰、更易读,并与React的声明性本质一致。1)useState允许在函数组件中直接声明状态变量,2)它通过钩子机制在重新渲染间记住状态,3)使用useState可以利用React的优化如备忘录化,提升性能,4)但需注意只能在组件顶层或自定义钩子中调用,避免在循环、条件或嵌套函数中使用。

何时使用usestate()以及何时考虑替代状态管理解决方案何时使用usestate()以及何时考虑替代状态管理解决方案Apr 24, 2025 pm 04:49 PM

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

React的可重复使用的组件:增强代码可维护性和效率React的可重复使用的组件:增强代码可维护性和效率Apr 24, 2025 pm 04:45 PM

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionComponcontRossDifferentPartsofanApplicationorprojects.1)heSredunceReDunceNundSimplifyUpdates.2)yessistensistencyInusErexperience.3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器