仅在一个方向上限制拖动

Utt*_*ara 6 draggable jquery-ui-draggable jquery-draggable

使用jQuery Draggable

如何限制拖动只能在一个方向上拖动?
即,只有当时只有顶部或者只有底部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'});
       }
   }
});
Run Code Online (Sandbox Code Playgroud)

Utt*_*ara 6

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

根据具体情况说,当轴:'y'时,只允许向下拖动

<div class="draggable">draggable only downwards</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.draggable {
    position:absolute;
    top:0px;
    background:pink;
    height:100px;
    width:100%;
    left: 0px;
    text-align:center;
}
Run Code Online (Sandbox Code Playgroud)

脚本

$('.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]);
});
Run Code Online (Sandbox Code Playgroud)

演示链接