简体   繁体   English

可拖动-如何限制可拖动元素越过屏幕底部?

[英]Draggable - How to restrain draggable element from going past the bottom of screen?

I have an element which is draggable only by the Y-axis. 我有一个只能在Y轴上拖动的元素。 I want it to be able to go past the top of the screen (which it can), but forbid it from going past the bottom of the screen. 我希望它能够超过屏幕顶部(可以),但禁止它越过屏幕底部。 I read in a jQuery Draggable API about containment, but found no answer as to the question I'm asking, or at least could not understand how to apply it to my case. 我在jQuery Draggable API中阅读了有关遏制的信息,但没有找到关于我所问问题的答案,或者至少不了解如何将其应用于我的案例。 Here's my code so far: 到目前为止,这是我的代码:

JavaScript: JavaScript:

$(document).ready(function() {
    $("#elem").draggable({
       axis: "y"
    });
});

There must be a better way but; 必须有更好的方法,但是;

$(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();
            }
       }
    });
});

You need to set the containment option to something that is the height of the page. 您需要将containment选项设置为页面的高度。

$(document).ready(function() {
    $("#elem").draggable({
       containment: "document",
       scroll: false,
       axis: "y"
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM