【问题标题】:Draggable jQuery Restriction可拖动的 jQuery 限制
【发布时间】:2017-08-22 22:00:08
【问题描述】:

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

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

任何人都可以帮助我吗?

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",
});

【问题讨论】:

    标签: javascript jquery css jquery-ui draggable


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。这个脚本的问题是它移动了整个页面,我需要一个不受移动影响的静态元素。像这个例子:[链接](urban-walks.com/#map)。有什么建议吗?
    • 你也可以将它适配为jQuery可拖动,主要思想是一样的。
    • 这正是我所需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2011-03-15
    • 2010-12-04
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多