1. 程式人生 > 程式設計 >基於jQuery拖拽事件的封裝

基於jQuery拖拽事件的封裝

本文例項為大家分享了基於jQuery封裝的拖拽事件,供大家參考,具體內容如下

HTML程式碼:

<!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;
      /* 讓文字無法被選中 */
      user-select:none;
    }
  </style>
</head>
<body>
  <div class="box"></div>box</div>
  <script>
    $('.box').Drag();//直接呼叫Drag()方法就可以了
  </script>
</body>
</html>

封裝的jQuery拖拽事件:

;(function($) {
  $.fn.extend({
    Drag(){
      //把this存起來,始終指向操作的元素
      _this = this;
      this.on('mousedown',function (e) {
        //盒子距離document的距離
        var positionDiv = $(this).offset();
        //滑鼠點選box距離box左邊的距離
        var distenceX = e.pageX - positionDiv.left;
        //滑鼠點選box距離box上邊的距離
        var distenceY = e.pageY - positionDiv.top;
        $(document).mousemove(function(e) {
          //盒子的x軸
          var x = e.pageX - distenceX;
          //盒子的y軸
          var y = e.pageY - distenceY;
          //如果盒子的x軸小於了0就讓他等於0(盒子的左邊界值)
          if (x < 0) {
            x = 0;
          } 
          //盒子右邊界值
          if(x > $(document).width() - _this.outerWidth()){
            x = $(document).width() - _this.outerWidth();
          }
          //盒子的上邊界值
          if (y < 0) {
            y = 0;
          }
          //盒子的下邊界值
          if(y > $(document).height() - _this.outerHeight()){
            y = $(document).height() - _this.outerHeight();
          }
          //給盒子的上下邊距賦值
          $(_this).css({
            'left': x,'top': y
          });
        });
        //在頁面中當滑鼠抬起的時候,就關閉盒子移動事件
        $(document).mouseup(function() {
          $(document).off('mousemove');
        });
      })
      //把this返回回去繼續使用jqurey的鏈式呼叫
      return this
    }
  })
})(jQuery) 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。