从CSS“top”到“bottom”的jQuery动画

我想在页面加载时将div元素从绝对顶部位置设置为绝对底部位置。

下面的CSS和jQuery代码的组合无法移动任何东西:

CSS

#line-three { position:absolute; width:100%; left:0px; top:113px; } 

jQuery的

  $("#line-three").animate({ bottom: "100px", }, 1200); 

谢谢您的帮助!

编辑:

我已经尝试将其更改为此(根据graphicdevine的建议),但仍然没有雪茄:

 var footerOffsetTop = $('#line-three').offset().bottom; $('#line-three').css({position:'absolute',top:'',bottom:footerOffsetTop}) $("#line-three").delay(100).animate({ bottom: '100px', }, 1200); 

我最终想出了一个解决方案……

基本上你从旧的top位置到另一个位置的动画也是相对于你通过取window高度计算的top并从bottom减去(1)所需位置,和(2)你想要动画的元素的高度。 然后,在动画结束时添加一个回调来更改css,然后元素位于底部值和顶部auto

这是jQuery脚本:

 $('#click').click(function () { var windowHeight = $(window).height(); var lineHeight = $('#line').height(); var desiredBottom = 100; var newPosition = windowHeight - (lineHeight + desiredBottom); $('#line').animate({top:newPosition},1000,function () { $('#line').css({ bottom: desiredBottom, top: 'auto' }); }); }); 

你可以看到它在这个jsFiddle中工作

您可以设置top:auto with .css方法然后设置animate:

 $(document).ready(function(){ $("#line-three").css({top:'auto'}); $("#line-three").animate({bottom:'100px'}, 200) }) 

编辑:

您可以使用正文/屏幕的大小进行游戏,并将顶部位置转换为底部位置,然后设置为所需的底部位置:

 $(document).ready(function(){ var bodyHeight = $('body').height(); var footerOffsetTop = $('#line-three').offset().top; var topToBottom = bodyHeight -footerOffsetTop; $('#line-three').css({top:'auto',bottom:topToBottom}); $("#line-three").delay(100).animate({ bottom: '100px', }, 1200); 

})

示例: http : //jsfiddle.net/reWwx/4/

也许这会有所帮助?

 $(document).ready( function() { var div = jQuery("#dvVertigo"); div.animate({ left: '0', top: '+=' + ($(window).height()-20) }, 5000, function () { // Animation complete. }); }); 

完整代码:

http://jsfiddle.net/yyankowski/jMjdR/

如果你想要动画,你应该这样做:

 $("#line-three").animate({ top: "500px", }, 1200); 

在这里小提琴: http : //jsfiddle.net/nicolapeluchetti/xhHrh/

你可以用它来动画它: 看看这个JSFiddle:

 $('#button').click(function(e){ // On click of something e.preventDefault(); // Prevent the default click aciton $("#line-three").animate({ top: "300px", }, 1200); }); 

$("#line-three").css({position:'absolute',top:'auto',bottom:'100px'})

应该这样做。 您可能需要将’top’值重新设置为auto

编辑

要进行动画处理,您需要使用.animate();

试试这个:

$("#line-three").animate({position:'absolute',top:'auto',bottom:'100px'}, 400)

可能是:

  $("#line-three").animate({position:'absolute',top:'auto',bottom:'100px'},1200) 

编辑

是的,这比第一次出现的要复杂。 你可能需要分析它相对于它的容器的当前位置(使用offset )并从那里开始工作。

编辑:不得不快速离开,所以没有完成,我决定使用jquery ui作为例子(你需要核心):

       
hello;

http://jsfiddle.net/syVzK/1/ (更改了切换开关以防止过度动画)

我也喜欢其他一些建议。

EDIT2:刚刚在IE中测试过……它的工作原理很奇怪。 也许必须直接因为IE中的奇怪行为与Jquery UI开关类。

编辑3

好吧,我让这个适用于IE和FF …虽然有些注意事项。 +20是为了防止跳跃。 对于innerHeight为0的测试是在没有为元素(或主体)设置高度的情况下,因此如果它位于已定位的div中,则设置高度。

此外,这在jsfiddle中不起作用 ,但在常规网页上工作。 为此,请避免使用jsfiddle。

   

您可以通过以下方式设置当前最低值:css(’bottom’)。 这对我有用(jQuery1.7.2):

 $('#line-three').css({bottom:$('#line-three').css('bottom'), top:'auto'}); $('#line-three').animate({ bottom: position }, 250);