我有一个可以垂直拖出屏幕的 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“可拖动”使用属性 top
,因为我查看了 Google Chrome 的调试器工具,当我拖动它时动态插入内联样式,我读到 top: -(x)px;
在我拖动 div 的同时继续爬升。所以,从逻辑上讲,我测试了它是否被拖动到 -340px
然后自动将它拖动到剩下的地方。
而且,如果可能的话,我希望 div 下降(使用 revert
?)如果它没有超过 -340px
,但事实并非如此确实是个大问题。
最佳答案
你的条件不对;你应该在 Drag even 被触发后进行验证!
查看下面的代码,检查位置是否高于 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>
关于javascript - jQuery - 可拖动 UI - 如何检测元素是否已被拖动到某个位置,然后调用动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665133/