7

使用jQuery 可拖动

如何限制可拖动对象只能在一个方向拖动?
即仅在顶部或仅底部时axis: 'y'
以及仅在左侧或仅在右侧时axis: 'x'

这意味着如果我只想将一个可拖动对象(with axis set to 'y')拖到bottom,那么它不应该能够将它拖到顶部,即当试图向顶部拖动时它应该保持在原位

这是我尝试过但不起作用的方法,即可拖动仍然向上拖动

$('. draggable').draggable({
    axis: 'y',
    handle: '.top'
    drag: function( event, ui ) {
       var distance = ui.originalPosition.top - ui.position.top;

       // if dragged towards top
       if (distance > 0) { 
           //then set it to its initial state
           $('.draggable').css({top: ui.originalPosition.top + 'px'});
       }
   }
});
4

2 回答 2

6

回答我自己的问题(除了上述答案之外的其他选择)以帮助他人

以特定情况为例,当轴:'y'时只允许向下拖动

<div class="draggable">draggable only downwards</div>

css

.draggable {
    position:absolute;
    top:0px;
    background:pink;
    height:100px;
    width:100%;
    left: 0px;
    text-align:center;
}

脚本

$('.draggable').draggable({
    axis: "y"
});    

$('.draggable').on('mousedown', function() {
    var x1 = x2 = $(".draggable").position().left;
    var y1 = $(".draggable").position().top;
    var y2 = ($(window).height() + $(".draggable").position().top);
    $(".draggable").draggable('option', 'containment', [x1, y1, x2, y2]);
});

演示链接

于 2013-05-14T06:15:14.173 回答
2

方法 1 - 使用 Revert Hack

jsFiddle

 $('.draggable').draggable({
     axis: "y",
     start: function (event, ui) {
         start = ui.position.top;
     },
     stop: function (event, ui) {
         stop = ui.position.top;

         if (start > stop) {
             $('.draggable').css({top: ui.originalPosition.top + 'px'});
         }
     }
 });

方法 2 - 禁用拖动而不还原

jsFiddle 2

基本上方法2只是将可拖动元素限制在容器中,并使用可拖动元素移动容器。看看,它出奇地简单,但有效。

$('.draggable').draggable({
    axis: "y",
    containment: "#containment-wrapper",
    scroll: true,
    scrollSensitivity: 100,
    scrollSpeed: 25,
    cursor: '-moz-grabbing'
});
$('.draggable').mousemove(function () {
    var x = $('.draggable').css('top');
    $("#containment-wrapper").css({
        top: x
    });
});

方法3 效果和方法2一样,只是使用了拖拽功能。

jsFiddle 3

$('.draggableDown').draggable({
    axis: "y",
    containment: "#containment-wrapperDown",
    scroll: true,
    scrollSensitivity: 100,
    scrollSpeed: 25,
    cursor: '-moz-grabbing',
    drag: function () {
        var x = $('.draggableDown').position().top;
        $("#containment-wrapperDown").css({
            top: x
        });
    }
});
于 2013-05-11T05:01:47.327 回答