欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于jQuery拖拽事件的封裝

 更新時(shí)間:2020年11月29日 09:50:19   作者:Spicy boy  
這篇文章主要為大家詳細(xì)介紹了基于jQuery拖拽事件的封裝,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了基于jQuery封裝的拖拽事件,供大家參考,具體內(nèi)容如下

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

封裝的jQuery拖拽事件:

;(function($) {
  $.fn.extend({
    Drag(){
      //把this存起來(lái),始終指向操作的元素
      _this = this;
      this.on('mousedown',function (e) {
        //盒子距離document的距離
        var positionDiv = $(this).offset();
        //鼠標(biāo)點(diǎn)擊box距離box左邊的距離
        var distenceX = e.pageX - positionDiv.left;
        //鼠標(biāo)點(diǎn)擊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
          });
        });
        //在頁(yè)面中當(dāng)鼠標(biāo)抬起的時(shí)候,就關(guān)閉盒子移動(dòng)事件
        $(document).mouseup(function() {
          $(document).off('mousemove');
        });
      })
      //把this返回回去繼續(xù)使用jqurey的鏈?zhǔn)秸{(diào)用
      return this
    }
  })
})(jQuery) 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論