左右模块滑动

 <!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .box1 {
       50px;
      height: 50px;
      background: red;
      position: absolute;
      top: 0;
      left: 50px;
    }

    .box2 {
       50px;
      height: 50px;
      background: blue;
      position: absolute;
      top: 56px;
      left: 0;
    }

    .line {
      height: 2px;
       100%;
      background: yellow;
      top: 52px;
      left: 0;
      position: relative;
    }

    .block {
      background: green;
      height: 100%;
      /*  100%; */
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>

<body>
  <div class="box1" style="left:50px;" id="box1"></div>
  <div class="line">
    <div class="block" id="block"></div>
  </div>
  <div class="box2" style="left:0;" id="box2"></div>
  <script>
    function Drag(id) {
      this.oDiv = document.getElementById(id);
      this.disX = 0;
    }
    Drag.prototype.init = function () {
      var self = this;
      this.oDiv.ontouchstart = function (ev) {
        var ev = ev || window.event;
        self.fnDown(ev);
        return false;
      };
    };
    Drag.prototype.fnDown = function (ev) {
      var self = this;
      this.disX = ev.touches[0].clientX - this.oDiv.offsetLeft;
      this.oDiv.ontouchmove = function (ev) {
        var ev = ev || window.event;
        self.fnMove(ev);
      };
      this.oDiv.ontouchend = this.fnUp.bind(this);

    };
    Drag.prototype.fnMove = function (ev) {
      var l = ev.touches[0].clientX - this.disX;
      //水平滚动
      this.oDiv.style.left = DragClac(l, ev) + 'px';
    };

    function DragClac(d, ev) {
      var id = ev.target.id;
      var left = 0;
      var right = window.innerWidth - 50;
      var block = document.getElementById("block");
      if (id === 'box1') {
        left = parseInt(document.getElementById('box2').style.left) + 50;
      }
      if (id === 'box2') {
        right = parseInt(document.getElementById('box1').style.left) - 50;
      }

      if (d <= left) {
        d = left;
      } else if (d >= right) {
        d = right;
      }
      if (id === 'box1') {
        block.style.right = (window.innerWidth - d) + "px";
        block.style.left = (left) + "px";
      }
      if (id === 'box2') {
        block.style.right = (window.innerWidth - right - 50) + "px";
        block.style.left = (d + 50) + "px";
      }
      return d;
    }

    Drag.prototype.fnUp = function () {
      this.oDiv.ontouchmove = null;
      this.oDiv.ontouchend = null;
    };

    var drag1 = new Drag("box1");
    drag1.init()
    var drag2 = new Drag("box2");
    drag2.init()
  </script>
</body>

</html>
原文地址:https://www.cnblogs.com/restart77/p/13377462.html