![](/img/trans.png)
[英]jquery ui draggable restricting div to up and down drag within containment
[英]jQuery UI Draggable set drag length without containment property
我有一個沒有任何父元素的div,並且我希望可拖動的DIV拖動到頂部和底部,但不能一直拖動到頂部。 我已經使用了頂部
drag: function (event, ui) {
if(ui.position.top < 50)
ui.position.top = 50;
},
但是,我想不出辦法做到這一點。 將元素拖動到底部時,我需要防止它從某個位置拖動。
HTML
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
jQuery的
$( "#draggable" ).draggable({
axis: 'y',
containment: 'window',
scroll: false,
cancel: false,
drag: function (event, ui) {
if(ui.position.top < 50)
ui.position.top = 50;
},
});
您需要父/容器的高度來計算底部偏移量:
$("#draggable").draggable({
axis: 'y',
containment: 'window',
scroll: false,
cancel: false,
drag: function (event, ui) {
var offset = 50;
var maxHeight = (window.innerHeight - this.offsetHeight - offset);
if (ui.position.top < offset) {
ui.position.top = offset;
return false;
}
else if (ui.position.top > maxHeight) {
ui.position.top = maxHeight;
return false;
}
}
});
取消或基本超出拖動效果時,可能需要返回false
才能取消或“釋放”拖動效果。
這是您所做的上述更改的小提琴:
$("#draggable").draggable({ axis: 'y', containment: 'window', scroll: false, cancel: false, drag: function(event, ui) { var offset = 50; var maxHeight = (window.innerHeight - this.offsetHeight - offset); if (ui.position.top < offset) { ui.position.top = offset; //return false; } else if (ui.position.top > maxHeight) { ui.position.top = maxHeight; //turn false; } }, });
html { overflow: hidden; } .ui-widget-content { width: 100%; padding: 15px; }
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/overcast/jquery-ui.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> <div id="draggable" class="ui-widget-content"> <p>Drag me around</p> </div>
考慮到div沒有父級,並且要將其拖到整個文檔中,應將其添加到代碼中
$( "#draggable" ).draggable({
axis: 'y',
containment: 'window',
scroll: false,
cancel: false,
drag: function (event, ui) {
if(ui.position.top < 50)
ui.position.top = 50;
if(ui.position.top > $(document).height() - 50)
ui.position.top = $(document).height() - 50;
},
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.