jQuery - 可拖动的UI - 如何检测元素是否已拖动到某个位置,然后调用动画



我有这个div,可以垂直拖出屏幕。我想知道是否有办法检测该div 是否已达到某个限制,然后显示一个动画,它会自动滑出页面。到目前为止,我认为我所做的应该有效,但是唉,我对JavaScript的平庸知识已经导致了它的丑陋结局。这是我到目前为止所拥有的:

$(document).ready(function() {
    $("div").draggable({
       axis: "y", // vertical drag only
       drag: function(event, ui) { // THIS NEXT BLOCK JUST MAKES SURE IT WON'T DRAG OFF THE BOTTOM OF SCREEN
            if($(this).offset().top + $(this).outerHeight() > $(window).height()) {
                $(this).offset({"top": $(window).height() - $(this).outerHeight()});
                event.preventDefault();
            }
       }
    });
    if($("div").css("top") == "-340px") {
        $("div").animate({
            top: "-100%"
        });
    }
});

我知道jQuery UI"Draggable"使用属性top因为我查看了Google Chrome的调试器工具,并且在拖动它时动态插入内联样式,并且我阅读top: -(x)px;在拖动div时继续攀爬。所以,从逻辑上讲,我测试了它是否被拖动通过-340px然后自动拖动它。

而且,如果可能的话,如果div 没有超过 -340px,我希望div 下降(使用 revert ?),但这实际上不是一个大问题。

您的状况不在正确的位置; 一旦触发了 Drag 甚至,您应该进行验证!

请参阅下面的代码,检查位置是否高于 100 并触发动画:

<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<div id="draggable" class="ui-widget-content ui-draggable" style="position: relative;">
    <p>Drag me around</p>
</div>
<script>
$(document).ready(function() {
    $("div").draggable({
       axis: "y", // vertical drag only
       drag: function(event, ui) { // THIS NEXT BLOCK JUST MAKES SURE IT WON'T DRAG OFF THE BOTTOM OF SCREEN
            if($(this).offset().top + $(this).outerHeight() > $(window).height()) {
                $(this).offset({"top": $(window).height() - $(this).outerHeight()});
                event.preventDefault();
            }
             if(Number($("div").css("top").replace("px","")) > 100) {
                $("div").animate({
                    top: "-100%"
                });
            }
       }
    });
});
</script>
</body>
</html>

最新更新