我有一个只能由 Y 轴拖动的元素。我希望它能够越过屏幕顶部(它可以),但禁止它越过屏幕底部。我阅读了关于遏制的 jQuery Draggable API,但没有找到关于我所问问题的答案,或者至少无法理解如何将其应用于我的案例。到目前为止,这是我的代码:
JavaScript:
$(document).ready(function() {
$("#elem").draggable({
axis: "y"
});
});
我有一个只能由 Y 轴拖动的元素。我希望它能够越过屏幕顶部(它可以),但禁止它越过屏幕底部。我阅读了关于遏制的 jQuery Draggable API,但没有找到关于我所问问题的答案,或者至少无法理解如何将其应用于我的案例。到目前为止,这是我的代码:
JavaScript:
$(document).ready(function() {
$("#elem").draggable({
axis: "y"
});
});
必须有更好的方法,但是;
$(document).ready(function() {
$("#elem").draggable({
axis: "y",
drag: function(event, ui) {
if($(this).offset().top + $(this).outerHeight() > $(window).height()) {
$(this).offset({"top": $(window).height() - $(this).outerHeight()});
event.preventDefault();
}
}
});
});
您需要将包含选项设置为页面高度。
$(document).ready(function() {
$("#elem").draggable({
containment: "document",
scroll: false,
axis: "y"
});
});