Using object-oriented thinking to achieve JS calculator

The following code updates will be put in my GitHub for a star

<! DOCTYPEhtml>
<html lang="">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Calculator</title>
    <link rel="stylesheet" href="./css/calculator.css">
</head>
<body>
    <div id="calculator">
        <! -- Display the calculation process and results of the box -->
        <div class="show_box">
            <! Results - - - >
            <div class="result">
                <span></span>
            </div>
            <! Process -- -- -- >
            <div class="show">
                <span></span>
            </div>
        </div>
        <! -- Input button -->
        <div class="inputtedBtns">
            <ul>
                <li>7</li>
                <li>8</li>
                <li>9</li>
                <li>/</li>
            </ul>
            <ul>
                <li>4</li>
                <li>5</li>
                <li>6</li>
                <li>*</li>
            </ul>
            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>+</li>
            </ul>
            <ul>
                <li>0</li>
                <li id="clean">c</li>
                <li>.</li>
                <li>-</li>
            </ul>
            <! -- equal to button -->
            <button class="equals_btn">=</button>
        </div>
    </div>
    <script src="./js/calculator.js"></script>
    <script>
        new Calculator().init();
    </script>
</body>
</html>
Copy the code
* {margin: 0;
  padding: 0;
}
ul{
  list-style: none;
}
body{
  background-color: #34495e;
}
#calculator{
  width: 330px;
  height: 480px;
  margin: 100px auto;
}
#calculator span{
  display: inline-block;
  font-size: 32px;
}
#calculator .show_box{
  background-color: #fff;
  height: 150px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  display: flex;
  flex-direction: column;
}
#calculator .show_box .result.#calculator .show_box .show{
  text-align: right;
  height: 50%;
  margin: 15px;
  overflow: hidden;
}
#calculator .show_box .result{
  color: salmon;
}

#calculator .inputtedBtns{
  position: relative;
  cursor: pointer;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  width: 330px;
  height: 330px;
  color: #657b8f;
  font-size: 25px;
  text-align: center;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  background: linear-gradient(to bottom,#e6f5ff 1%.#fff 8%);
  /* Settings text cannot be selected */
  user-select: none;
} 
#calculator .inputtedBtns ul{
  display: flex;
  flex-grow: 1;
  font-size: 25px;
}
#calculator .inputtedBtns li{
  width: 25%;
  line-height: calc(320px/4);
}
#calculator .inputtedBtns ul li:last-of-type{
  color: #58b3ff;
}
#calculator .inputtedBtns ul:last-of-type #clean{
  color: #ED4C67;
}
#calculator .inputtedBtns ul:last-of-type li:nth-child(3) {line-height: 70px;
  color: #58b3ff;
}
#calculator .equals_btn{
  width: 150px;
  height: 40px;
  border-radius: 5px;
  border: none;
  background-color: #58b3ff;
  color: #fff;
  font-size: 30px;
  outline: none;
  position: absolute;
  right: 50%;
  bottom: -30px;
  transform: translateX(50%);
}
Copy the code
; (function (doc) {
  function Calculator() {
      // Display the calculation process and results of the box
      this.showBox = doc.getElementsByClassName('show_box') [0];
      // Input button
      this.inputtedBtns = doc.getElementsByClassName('inputtedBtns') [0];
      this.equalsBtn = doc.getElementsByClassName('equals_btn') [0];
      this.result = this.showBox.querySelector('.result');
      this.resultChild = this.result.querySelector('span');
      this.show = this.showBox.querySelector('.show');
      this.showChild = this.show.querySelector('span');
      this.clean = this.inputtedBtns.querySelector('#clean');
      this.ul = this.inputtedBtns.querySelector('ul');
      this.fontSizeUl = parseInt(window.getComputedStyle(this.ul).fontSize);
      this.flag = true;
  }
  // Initialize method
  Calculator.prototype.init = function () {
      this.BindEvent();
  }
  // Event method
  Calculator.prototype.BindEvent = function () {
      this.inputtedBtns.addEventListener('click'.this.onClickObtain.bind(this), false);
      this.equalsBtn.addEventListener('click'.this.onClickResult.bind(this));
      this.clean.addEventListener('click'.this.onClickClean.bind(this))}/ / use event delegation, click get elements (about event delegation: https://blog.csdn.net/m0_46217225/article/details/115328572?spm=1001.2014.3001.5501)
  Calculator.prototype.onClickObtain = function (e) {
      let elemLi = e.target;
      // Call the font change animation method
      Calculator.sizeAnimation(elemLi, this.fontSizeUl);
      // Invoke the overflow handling method
      if(this.showChild.clientWidth >= this.show.clientWidth && this.flag){
          Calculator.valOverflow(this.show);
          this.flag = false;
      }
      if (elemLi.tagName.toLowerCase() === 'li'&& elemLi.id ! ="clean") {
          this.displayProcess(elemLi.innerText); }}// Font change animation method (this creates callback hell, can be overwritten with promise)
  Calculator.sizeAnimation = function (elem, size) {
      let raise = setInterval(() = > {
          elem.style.fontSize = size + 1 + 'px'
          size++;
          if (size >= 34) {
              clearInterval(raise);
              let decline = setInterval(() = > {
                  elem.style.fontSize = size - 1 + 'px';
                  size--;
                  if (size <= 25) {
                      elem.style.fontSize = 25 + 'px';
                      clearInterval(decline); }},15); }},15);
  }
  // display the calculation process
  Calculator.prototype.displayProcess = function (elem) {
      this.showChild.innerText += elem;
  }
  // Click the result
  Calculator.prototype.onClickResult = function () {
      if (this.showChild.innerHTML ! ="") {
          this.resultChild.style.fontSize = this.showChild.style.fontSize;
          this.resultChild.innerHTML = eval(this.show.innerText); }}// Click Clear
  Calculator.prototype.onClickClean = function () {
      // Clear the child element
      let showChild = this.showChild;
      showChild.innerText = "";
      showChild.style.fontSize = '32px'
      this.flag = true;
      // Clear the result
      this.resultChild.innerText = "";
  }
  // Overflow processing
  Calculator.valOverflow = function (elem) {
      // Set the observer options to observe the changes (observe the addition and deletion of children of the target node)
      let config = { childList: true.subtree: true }
      // Set the observer callback function
      function callback(records) {// Record the changes in the array
          let rs = records[0].target;
          if (rs.clientWidth > rs.parentNode.clientWidth) {   
              rs.style.fontSize = parseInt(window.getComputedStyle(rs).fontSize) - 5 + 'px';
              // Clear mutation observer
              if(parseInt(elem.children[0].style.fontSize) <= 12){ observer.disconnect(); }}}// Create an instance object of MutationObserver
      let observer = new MutationObserver(callback);
      // Add elements and changes to observe
      observer.observe(elem, config);
  }
  window.Calculator = Calculator; }) (document);
Copy the code
You can also follow me if you are interested:

CNSD: m0_46217225

Nuggets: buzz cut boy

Making: Buzz_cut

Wechat official account: web_mycode

Man with a buzz cut

Welcome to join QQ group to exchange programming knowledge:

Qq group: 808752665

My QQ: 2356924146

I will continue to share programming tips.