按住鼠標右鍵(或觸摸)拖動帶 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,防止拖動時誤選)。px, py 與鼠標頁面坐標 pageX, pageY。dx = x - prevX,反向設置 scrollLeft = px - dx。e.touches[0] 獲取首個觸點。lastPX/lastPY 檢測是否已達滾動極限,防止抖動。