如何限制拖动只能在一个方向上拖动 ?
即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'});
}
}
});
答案 0 :(得分: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]);
});
<强> Demo Link 强>
答案 1 :(得分:2)
方法1 - 使用还原黑客
<强> 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
});
}
});