如果您需要通過拖動滾動,不使用拖動。改用簡單的鼠標移動。看下面的例子。在這種情況下,您可以滾動容器內的任何內容。 希望它會有所幫助。
已更新: 如果需要拖動一些背景元素,您應該通過mousemove拖動它並根據容器大小計算可見區域。
因此,用幾句話 - 拖動圖像,直到它的width
減去left offset
大於container(window) width
,依此類推,右,上和下偏移。
// Main script
function run() {
var $image = $('#draggable');
var $window = $(window);
var isStarted = false;
var cursorInitialPosition = {left: 0, top: 0};
var imageInitialPosition = {left: 0, top: 0};
var imageSize = {width: $image.width(), height: $image.height()};
// stop dragging
var stop = function() {
isStarted = false;
$window.unbind('mousemove', update);
};
// update image position
var update = function(event) {
// size of container (window in our case)
var containerSize = {width: $window.width(), height: $window.height()};
var left = imageInitialPosition.left + (event.pageX - cursorInitialPosition.left);
var top = imageInitialPosition.top + (event.pageY - cursorInitialPosition.top);
// don't allow dragging too left or right
if (left <= 0 && imageSize.width + left >= containerSize.width) {
$image.css('left', left);
}
// don't allow dragging too top or down
if (top <= 0 && imageSize.height + top >= containerSize.height) {
$image.css('top', top);
}
};
$window.mousedown(function(event){
var position = $image.position();
cursorInitialPosition.left = event.pageX;
cursorInitialPosition.top = event.pageY;
imageInitialPosition.left = position.left;
imageInitialPosition.top = position.top;
$(window).mousemove(update);
});
$window.mouseout(stop);
$window.mouseup(stop);
}
$(function(){
// wait for image loading because we need it size
var image = new Image;
image.onload = run;
image.src = "http://cdn.wallpapersafari.com/10/37/Aim58J.jpg";
});
https://jsfiddle.net/2hxz49bj/5/
謝謝回答。這個腳本的問題在於它移動了整個頁面,我需要一個不受移動影響的靜態元素。就像這個例子:[link](http://urban-walks.com/#map)。有什麼建議麼? –
請參閱我的更新回答 –
你也可以適應jQuery可拖動,主要想法將是相同的。 –