萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 拖拽滾動插件:dragScroll 實現鼠標拖動溢出元素

插件功能

按住鼠標右鍵(或觸摸)拖動帶 overflow:auto/scroll 的容器,實現類地圖拖拽瀏覽效果,支援移動端觸摸事件。

核心代碼結構

(function($){
  var down=false, prevX=0, prevY=0, x=0, y=0, px=0, py=0, lastPX=-1, lastPY=-1;
  var $target=null, $me=null, $selector="";
  var settings = { mouseButton: 3, context: false, selectText: false };

  $.fn.dragScroll = function(options){
    settings = $.extend(settings, options);
    $selector = $(this).selector;
    $(this).contextmenu(function(){ return false; })
      .bind("mousedown touchstart", function(e){
        $me = $(this);
        e = e.touches ? e.touches[0] : e;
        $target = $(e.target).closest($selector);
        if(settings.viewPort){ ... }
        if(!settings.selectText){ $me.attr('unselectable','on').css('user-select','none').on('selectstart',false); }
        $me = $me.closest($selector);
        if($target && $me.attr("id") != $target.attr("id")) return false;
        if(e.which == settings.mouseButton || e.touches){
          $me.css("cursor","move"); down=true;
        }
        px = $me.scrollLeft(); py = $me.scrollTop();
        x = px + e.pageX; y = py + e.pageY;
        prevX = x; prevY = y;
        return true;
      })
      .bind("mouseup touchend", function(e){
        $me = $(this); e = e.touches ? e.touches[0] : e;
        $me.css("cursor","auto"); down=false;
      })
      .bind("mousemove touchmove", function(e){
        $me = $(this).closest($selector);
        e = e.touches ? e.touches[0] : e;
        if((e.which == settings.mouseButton || e.touches) && down){
          if(e.touches) e.preventDefault();
          if($target && $me.attr("id") != $target.attr("id")) return false;
          $me.css("cursor","move");
          px = $me.scrollLeft(); py = $me.scrollTop();
          x = px + e.pageX; y = py + e.pageY;
          $me.scrollLeft(px - (x - prevX));
          $me.scrollTop(py - (y - prevY));
          prevX = x - (x - prevX); prevY = y - (y - prevY);
          if(lastPX == px) prevX = x;
          if(lastPY == py) prevY = y;
          lastPX = px; lastPY = py;
        }
        return true;
      });
    return this;
  };
})(jQuery);

使用方法

<div id="scrollContainer" style="width:500px;height:300px;overflow:auto;">
  <img src="large-map.jpg" width="2000" height="1500" />
</div>
<script>
$("#scrollContainer").dragScroll({ mouseButton: 1 }); // 左鍵拖動
</script>

配置選項

  • mouseButton:觸發拖動的鼠標鍵(1左鍵,2中鍵,3右鍵,默認 3)。
  • context:是否禁用右鍵菜單。
  • selectText:是否允許選中文字(默認 false,防止拖動時誤選)。

原理解析

  1. 記錄按下時滾動位置 px, py 與鼠標頁面坐標 pageX, pageY。
  2. 移動時計算偏移量 dx = x - prevX,反向設置 scrollLeft = px - dx。
  3. 觸摸事件兼容:e.touches[0] 獲取首個觸點。
  4. 邊界保護:lastPX/lastPY 檢測是否已達滾動極限,防止抖動。
copyright © 萬盛學電腦網 all rights reserved