可拖动 jQuery 限制

Draggable jQuery Restriction

我正在尝试通过拖动光标来滚动图像。我正在使用 Draggable jQuery 库,但我遇到了问题。

我需要确定图像的限制,以便我可以阻止拖动以避免显示白色space。

有人可以帮我吗?

jsfiddle

<div style="width:100%;height:100%;" id="parent">
<img src="http://cdn.wallpapersafari.com/10/37/Aim58J.jpg" id="draggable"/>

$( "#draggable" ).draggable({
    axis: 'x,y',
    cursor: "crosshair",
});

如果需要拖动滚动,请不要使用拖动。请改用简单的鼠标移动。看下面的例子。在这种情况下,您可以滚动容器内的任何内容。 希望对你有帮助。

更新: 如果需要拖拽一些背景元素,需要用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/