本文实例为大家分享了基于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) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持悠悠之家。

点赞(101)

评论列表共有 0 条评论

立即
投稿
返回
顶部