将键盘支持和退格添加到jQuery计算器

时间:2015-10-13 13:19:43

标签: javascript jquery html css calculator

如何为计算器和退格功能添加简单的键盘支持,以删除最后输入的数字(如果数字> 1)或.符号?另外,我需要同时使用.,符号来执行此类(1.02 + 1,02 = 2.04)

以下是完整代码:



// Calculator script

$(function() {

  // Main variables
  var $screen = $('.screen');
  var value = 0;
  var start = true;
  var action = 0;

  // Display '0' on load
  $screen.text('0');

  // Digits
  $('.digit').on('click', function() {
    var mytext = $(this).text();
    var curtext = (start) ? '0' : $screen.text();
    start = false;
    if (mytext == '.') {
      if (curtext.indexOf('.') < 0) {
        $screen.text(curtext + mytext);
      }
    } else {
      if (curtext === '0') {
        // Overwrite
        $screen.text(mytext);
      } else {
        $screen.text(curtext + mytext);
      }
    }
  });

  // Maths operations
  function Maths_operations() {
    var num = parseFloat($screen.text());
    switch (action) {
      case 0:
        { // Nothing?
          value = num;
        }
        break;
      case 1:
        { // Add
          value += num;
        }
        break;
      case 2:
        { // Subtract
          value -= num;
        }
        break;
      case 3:
        { // Multiply
          value *= num;
        }
        break;
      case 4:
        { // Divide
          if (num == 0) {
            value = 'Error'; // Couldn't divide by zero!
          } else {
            value /= num;
          }
        }
        break;
      default:
        break; // Shouldn't happen...
    }
    start = true; // New number now...
  }

  // Actions
  $('.action').on('click', function() {
    switch ($(this).text()) {
      case 'C':
        { // Clear
          value = 0;
          $screen.text('0');
          action = 0;
          start = true;
        }
        break;
      case '←':
        { // Delete last
          Maths_operations();
          action = 5;
        }
        break;
      case '\u00F7':
        { // Divide
          Maths_operations();
          action = 4;
        }
        break;
      case '\u00D7':
        { // Multiply
          Maths_operations();
          action = 3;
        }
        break;
      case '-':
        { // Subtract
          Maths_operations();
          action = 2;
        }
        break;
      case '+':
        { // Add
          Maths_operations();
          action = 1;
        }
        break;
      case '=':
        { // Equals
          Maths_operations();
          $screen.text(value);
          action = 0; // Nothing
        }
        break;
      default:
        { // If it's not a button
          console.log($(this).text());
        }
    }
  });

});
&#13;
/* Basic reset */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

  /* Global text styling */
  font-family: 'Roboto Mono', Helvetica, Arial, sans-serif;
}

/* Background */
html {
  height: 100%;
  background: rgba(171, 168, 168, 0.82);
  background-size: cover;
}

/* Name */
.pre-top > span {
  display: block;
  
  /* Special text styling */
  font-family: 'Josefin Slab', Monospace, sans-serif;
  font-size: 20px;
  line-height: 22px;
  letter-spacing: 2px;
  font-weight: bold;
  color: #000;
  text-align: center;
}

.pre-top .version {
  margin-bottom: 10px;
  font-size: 12px;
}

/* Calculator body */
.calculator {
  
  /* Absolute horizontal & vertical centering */
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  width: 400px;
  height: auto;
  padding: 20px 20px 9px;
  background: #b8c6cc;
  background: linear-gradient(#979fa2 14.9%, #6a7073 52.31%);
  border-radius: 3px;
  
  /* Using box shadows to create 3D effects */
  box-shadow: 0 4px #5e6264, 0 10px 15px rgba(0, 0, 0, 0.2);
}

/* Top */
.top span.clear {
  float: left;
}

.top .screen {
  height: 40px;
  width: 212px;
  float: right;
  padding: 0 10px;
  margin-bottom: 20px;
  /* Inset shadow on the screen to create some indent */
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  box-shadow: inset 0 4px rgba(0, 0, 0, 0.2);
  /* Typography */
  font-size: 17px;
  line-height: 40px;
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  text-align: right;
  letter-spacing: 1px;
}

/* Clear floats */
.keys,
.top {
  overflow: hidden;
}

/* Applying same to the keys */
.keys span,
.top span.clear,
.top span.backspace {
  float: left;
  position: relative;
  top: 0;
  cursor: pointer;
  width: 66px;
  height: 36px;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 4px rgba(0, 0, 0, 0.2);
  margin: 0 8px 11px 0;
  color: #000;
  line-height: 36px;
  text-align: center;
 
  /* Smoothing out hover and active states using css3 transitions */
  transition: all 0.2s ease;
  /* Prevent selection of text inside keys in all browsers*/
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.keys span {
  width: 84px;
}

/* Style different type of keys (operators/evaluate/clear) differently */
.keys span.operator {
  background: #f5ac75;
  /* Remove right margins from operator keys */
  margin-right: 0;
  color: #fff;
}

.keys span.eval {
  background: #79de9e;
  color: #fff;
}

.top span.clear,
.top span.backspace {
  background: #e79199;
  color: #fff;
}

/* Some hover effects */
.keys span:hover {
  background: #7d8ae3;
  box-shadow: 0 4px #5963a0;
  color: #fff;
}

.keys span.operator:hover {
  background: #fa9345;
  box-shadow: 0 4px #ce8248;
}

.keys span.eval:hover {
  background: #39f788;
  box-shadow: 0 4px #2fc66e;
  color: #fff;
}

.top span.clear:hover,
.top span.backspace:hover {
  background: #f86670;
  box-shadow: 0 4px #d5656d;
}

/* Simulating "pressed" effect on active state of the keys by removing the box-shadow and moving the keys down a bit */
.keys span:active {
  top: 4px;
  box-shadow: 0 0 #6b54d3;
}

.keys span.eval:active {
  top: 4px;
  box-shadow: 0 0 #717a33;
}

.top span.clear:active,
.top span.backspace:active {
  top: 4px;
  box-shadow: 0 0 #d3545d;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Some Google Fonts -->
<link href='https://fonts.googleapis.com/css?family=Josefin+Slab|Roboto+Mono:500' rel='stylesheet' type='text/css'>

<!-- Calculator -->
<div class="calculator">

  <!-- Name -->
  <div class="pre-top">
    <span class="name">jQuery calculator</span>
    <span class="version">v1.1</span>
  <div>

  <!-- Clear key & screen-->
  <div class="top">
    <span class="action clear">C</span>
    <span class="action backspace">←</span>
    <span class="screen"></span>
  </div>

  <!-- Operators and other keys -->
  <div class="keys">
    <span class="digit">7</span>
    <span class="digit">8</span>
    <span class="digit">9</span>
    <span class="action operator">+</span>
    <span class="digit">4</span>
    <span class="digit">5</span>
    <span class="digit">6</span>
    <span class="action operator">-</span>
    <span class="digit">1</span>
    <span class="digit">2</span>
    <span class="digit">3</span>
    <span class="action operator">&divide;</span>
    <span class="digit">0</span>
    <span class="digit">.</span>
    <span class="action eval">=</span>
    <span class="action operator">&times;</span>
  </div>
    
</div>
&#13;
&#13;
&#13;

Codepen版本。谢谢观看!

2 个答案:

答案 0 :(得分:1)

当我将快捷键添加到Web应用程序时,我最终使用了jwerty。我在jQuery中使用它,但它没有依赖项。

https://github.com/keithamus/jwerty

可以轻松指定键和事件处理程序。

jwerty.key('⌫', function () {
    //Code here to remove last char from calculator screen
});

注意:您必须确保浏览器窗口具有焦点,才能使关键快捷方式正常工作。

答案 1 :(得分:1)

我试过这个片段并且运行正常。 捕获退格的操作但实际上也未在鼠标键盘中实现。

$( "body" ).keydown(function( event ) {

  if ( event.which == 13 || event.which == 8) {
   event.preventDefault();
  }

    var input= mapKey(event.which);
    if(input == undefined)return;
    var mytext = input;


    var curtext = (start) ? '0' : $screen.text();
    start = false;
    if (mytext == '.' || mytext == ',' ) {
      if (curtext.indexOf('.') < 0) {
        $screen.text(curtext + mytext);
      }
    } else {
      if (curtext === '0') {
        // Overwrite
        $screen.text(mytext);
      } else if(jQuery.isNumeric(mytext)) {
        $screen.text(curtext + mytext);
      }
    }
   console.log(mytext);
    switch (mytext) {

  case 'c':
    { // Clear
      value = 0;
      $screen.text('0');
      action = 0;
      start = true;
    }
    break;
  case '←':
    { // Delete last
      Maths_operations();
      action = 5;
    }
    break;
  case '\u00F7':
    { // Divide
      Maths_operations();
      action = 4;
    }
    break;
  case '\u00D7':
    { // Multiply
      Maths_operations();
      action = 3;
    }
    break;
  case '-':
    { // Subtract
      Maths_operations();
      action = 2;
    }
    break;
  case '+':
    { // Add
      Maths_operations();
      action = 1;
    }
    break;
  case '=':      
    { // Equals
      Maths_operations();
      $screen.text(value);
      action = 0; // Nothing
    }
    break;
  default:
    { // If it's not a button
     // console.log($(this).text());
    }
}
function mapKey(myKey){
    switch(myKey){
      case 48:
      case 96:
      return "0";
      case 49:
      case 97:
      return "1";
      case 50:
      case 98:
      return "2";
      case 51:
      case 99:
      return "3";
      case 52:
      case 100:
      return "4";
      case 53:
      case 101:
      return "5";
      case 54:
      case 102:
      return "6";
      case 55:
      case 103:
      return "7";
      case 56:
      case 104:
      return "8";
      case 57:
      case 105:
      return "9";
      case 67:
      return "c";
      case 8:
      return '←';
      case 13:
      case 187:
      return '=';
      case 109:
      return '-';
      case 107:
      return '+';
      case 111:
      return '\u00F7';
      case 106:
      return '\u00D7';
      case 188:
      case 190:
      return '.';

    }
  }
  //$(this).text().append("");
});