使用jQuery .animate从右到左为div设置动画? [英] using jQuery .animate to animate a div from right to left?

查看:336
本文介绍了使用jQuery .animate从右到左为div设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绝对位于top: 0pxright: 0px的div,我想使用jquery的.animate()将其从当前位置动画化为left: 0px.如何做到这一点?我似乎无法使它正常工作:

I have a div absolutely positioned at top: 0px and right: 0px, and I would like to use jquery's .animate() to animate it from it's current position to left: 0px. How does one do this? I can't seem to get this to work:

$("#coolDiv").animate({"left":"0px"}, "slow");

为什么这样不起作用,一个人如何完成我想要做的事情?

Why doesn't this work and how does one accomplish what I am looking to do?

谢谢!

推荐答案

我认为它不起作用的原因与您设置了right位置而不是left有关.

I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left.

如果您将left手动设置为当前位置,它似乎可以运行:

If you manually set the left to the current position, it seems to go:

实时示例: http://jsfiddle.net/XqqtN/

var left = $('#coolDiv').offset().left;  // Get the calculated left position

$("#coolDiv").css({left:left})  // Set the left to its calculated position
             .animate({"left":"0px"}, "slow");


由于Firefox的计算出的left位置可以以像素为单位的正确值显示,因此Firefox看起来像预期的那样,而基于Webkit的浏览器(显然是IE)则为左侧位置返回auto值.

Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position.

由于auto并不是动画的起始位置,所以动画有效地从0开始运行到0.观看起来不是很有趣. :o)

Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)

如上所述,在设置动画之前手动设置左侧位置即可解决此问题.

Setting the left position manually before the animate as above fixes the issue.

如果您不喜欢用变量来弄乱风景,那么这是一个很好的版本,它消除了对变量的需要:

If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ​

这篇关于使用jQuery .animate从右到左为div设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆