将可拖动元素设置为底部动画

时间:2013-07-28 22:18:24

标签: jquery

我希望在拖动对象后,在一个平滑的移动中将对象动画回到其起始位置(底部/左侧)。 尽管如此,一切似乎都可以正常工作。 据我了解,这是因为只要尚未设置最高值,动画功能就无法计算移动。

我做了一个例子:

$("#move").click(function(){
    $(".block").animate({"bottom": "9px", "left": "9px"}, "slow");
});

http://jsfiddle.net/Tancrede/dztFw/3/

它不应该那么复杂,但我担心我的javascript / jquery技能非常有限。

有人提出了类似的问题,我的印象是我的情况比较简单,但我仍然不知道如何调整脚本。 Animating draggable object to its starting position

如果有人有时间帮助我会很棒!

1 个答案:

答案 0 :(得分:2)

  

我已经想出了一个解决方案,这可能看起来有点hacky但我现在想不出任何其他方式,因为draggable正在元素上设置top,而你除非你的元素没有任何固定的高度,否则当你有一个顶部时,它不能在底部。确实如此。

$( "#draggable" ).draggable({ containment: "window" });

$("#move").click(function(){
    var el = $('.block'); // Save the element
    el.animate({
       top: getHeight(el, 9), // Calculate the height with our function
       left: "9px"
    }, "slow");
});

var getHeight = function( elem, extra) {
    return $(window).height() - elem.height() - (extra || 0);
    // here we just calculate the height of the window minus the height of 
    // the element minus the extra 9px that you had by default, and we get a 
    // bottom:9px; effect.
};
  

在我的示例中,我们省略bottom并将使用top代替,我们计算窗口的height,然后取走height element 1}}以及你需要的任何额外费用。

Demo

  

如果我能想出更好的方法,我会将其添加到答案中。

     

注意 - 它无法正常运行的原因是因为它已经有top,您无法将top设为auto。或inherit所以它会直接跳到bottom