當容器內容超出可視範圍時,除了 scrollbar,還有一種更直覺的操作方式:按住滑鼠直接拖曳內容。以下這個 jQuery 插件實作了「拖曳捲動」(drag and scroll),並且同時支援觸控裝置。
/**
* jQuery Drag and Scroll
*
* Copyright (c) 2012 Ryan Naddy (ryannaddy.com)
* Dual licensed under the MIT and GPL licenses:
* https://www.opensource.org/licenses/mit-license.php
* https://www.gnu.org/licenses/gpl.html
*/
(function ($) {
var down = false;
var prevX = 0, prevY = 0;
var x = 0, y = 0;
var px = 0, py = 0;
var lastPX = -1, lastPY = -1;
var $target = null;
var $me = null;
var $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 = event.touches ? event.touches[0] : e;
$target = $(e.target);
$target = $target.closest($selector);
if (settings.viewPort) {
if (!settings.context) {
$me.contextmenu(function () { return false; });
}
}
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 || event.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 = event.touches ? event.touches[0] : e;
$me.css("cursor", "auto");
down = false;
}).bind("mousemove touchmove", function (e) {
$me = $(this);
$me = $me.closest($selector);
e = event.touches ? event.touches[0] : e;
if ((e.which == settings.mouseButton || event.touches) && down) {
if (event.touches) {
event.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);
整個插件的骨架是「記錄按下時的滑鼠座標與捲動位置,再在移動時算出位移差並反向套用」。更具體地說:
mousedown/touchstart 時,先把 scrollLeft 與 scrollTop 存進 px、py,再把「捲動量 + 頁面座標」合成一組絕對座標 x、y 作為基準點 prevX、prevY。
mousemove/touchmove 時,重新計算當前座標,用 scrollLeft(px - (x - prevX)) 把滑鼠往右拉的位移轉為內容往左捲,方向剛好符合「拖動紙張」的手感。
另外幾個細節值得一提:settings.mouseButton 預設為 3(右鍵),並搭配 contextmenu 回傳 false 來關閉右鍵選單;selectText: false 會停用文字選取,避免拖曳時反白;觸控環境則用 event.preventDefault() 阻止頁面本身的滾動行為,讓手勢交由插件處理。
只要對目標容器呼叫即可:
$('#viewport').dragScroll();
需要留意的是,這份程式碼寫於 2012 年,其中幾處在今日的環境下需要調整:$(this).selector 已在 jQuery 3.0 中移除,改用外傳的選擇器字串會更穩妥;event.touches 應改為 e.touches(此處直接用了全域 event,僅在非標準模式下偶然可行);mouseButton: 3 代表右鍵,一般使用者可能不習慣,實務上多改為 0(左鍵)並搭配游標樣式提示。若要移植到新專案,建議以 Pointer Events(pointerdown/pointermove/pointerup)重寫,就能用一套程式碼同時處理滑鼠、觸控與手寫筆。