Encapsulation based on jQuery drag event

  • 2021-09-24 21:28:43
  • OfStack

In this article, we share the drag-and-drop event based on jQuery encapsulation for your reference. The specific contents are as follows

HTML code:


<!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">
  <script src="jquery-3.4.1.min.js"></script>
  <script src="Drag.js"></script>
  <title>Document</title>
  <style>
    *{
      padding: 0;
      margin: 0;
    }
    .box{
      height: 200px;
      width: 200px;
      background-color: red;
      position: absolute;
      /*  Make the text unselectable  */
      user-select:none;
    }
  </style>
</head>
<body>
  <div class="box"></div>box</div>
  <script>
    $('.box').Drag();// Direct call Drag() The method will do 
  </script>
</body>
</html>

Encapsulated jQuery drag event:


;(function($) {
  $.fn.extend({
    Drag(){
      // Put this Save, always pointing to the element of the operation 
      _this = this;
      this.on('mousedown',function (e) {
        // Box distance document The distance of 
        var positionDiv = $(this).offset();
        // Mouse click box Distance box Distance to the left 
        var distenceX = e.pageX - positionDiv.left;
        // Mouse click box Distance box Distance above 
        var distenceY = e.pageY - positionDiv.top;
        $(document).mousemove(function(e) {
          // Boxed x Shaft 
          var x = e.pageX - distenceX;
          // Boxed y Shaft 
          var y = e.pageY - distenceY;
          // If the box's x The axis is less than 0 Let him be equal to 0 (The left boundary value of the box) 
          if (x < 0) {
            x = 0;
          } 
          // Right boundary value of box 
          if(x > $(document).width() - _this.outerWidth()){
            x = $(document).width() - _this.outerWidth();
          }
          // Upper boundary value of box 
          if (y < 0) {
            y = 0;
          }
          // Lower boundary value of box 
          if(y > $(document).height() - _this.outerHeight()){
            y = $(document).height() - _this.outerHeight();
          }
          // Assign values to the top and bottom margins of a box 
          $(_this).css({
            'left': x,
            'top': y
          });
        });
        // When the mouse is raised in the page, the box movement event is turned off 
        $(document).mouseup(function() {
          $(document).off('mousemove');
        });
      })
      // Put this Go back and continue to use jqurey Chain call of 
      return this
    }
  })
})(jQuery) 

Related articles: