Die Idee der Kapselung

<!DOCTYPE html>
<html lang="en">

<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>Document</title>
  <style>
    #box {
      width: 200px;
      height: 200px;
      background: blue;
    }
  </style>
</head>

<body>
  <button id="btn1">宽度到600px</button>
  <button id="btn2">宽度到800px</button>
  <div id="box"></div>
</body>
<script>
  var btn1 = document.getElementById("btn1");
  var btn2 = document.getElementById("btn2");
  var box = document.getElementById("box");
  var widthObj = 200;
  /* var step = 2;
  btn1.onclick = function () {
    var timer1 = setInterval(function () {
      if (widthObj < 600) {
        widthObj += step;
        box.style.width = widthObj + "px"
      } else {
        clearInterval(timer1)
      }
    }, 10)
  }
  btn2.onclick = function () {
    var timer1 = setInterval(function () {
      if (widthObj < 800) {
        widthObj += step;
        box.style.width = widthObj + "px"
      } else {
        clearInterval(timer1)
      }
    }, 10)
  } */
  // 封装的思想:
  /*
    可变化的量
    1、最大宽度      widthMax
    2、时间间隔      duration
    3、每一步走的距离 step
   */
  function changeWidth(widthMax, duration, step) {
    var timer1 = setInterval(function () {
      if (widthObj < widthMax) {
        widthObj += step;
        box.style.width = widthObj + "px"
      } else {
        clearInterval(timer1)
      }
    }, duration)
  }
  btn1.onclick = function () {
    changeWidth(600, 10, 2);
  }
  btn2.onclick = function () {
    changeWidth(800, 5, 1);
  }
</script>

</html>

Ich denke du magst

Origin blog.csdn.net/weixin_47619284/article/details/126755750
Empfohlen
Rangfolge