使用jQuery .animate从右到左动画div?

Ale*_*lex 42 jquery jquery-animate

我有一个div绝对定位于top: 0pxright: 0px,我想使用jquery .animate()来动画它从它的当前位置到left: 0px.怎么做到这一点?我似乎无法让这个工作:

$("#coolDiv").animate({"left":"0px"}, "slow");
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用,如何实现我想做的事情?

谢谢!!

use*_*716 50

我认为它不起作用的原因与你有right位置设置的事实有关,但不是left.

如果你手动设置left到当前位置,它似乎去:

实例: 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");
Run Code Online (Sandbox Code Playgroud)

编辑:

看起来好像Firefox的行为符合预期,因为它的计算left位置可用作像素的正确值,而基于Webkit的浏览器,显然是IE,返回auto左侧位置的值.

因为auto它不是动画的起始位置,所以动画有效地从0到0运行.观看不是很有趣.:O)

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


如果你不喜欢用变量混淆景观,这里有一个很好的同一个版本,可以避免变量的需要:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ?
Run Code Online (Sandbox Code Playgroud)


Abh*_*oel 6

这对我有用

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
Run Code Online (Sandbox Code Playgroud)


art*_*ung 5

这是一个最小的答案,显示您的示例工作:

<html>
<head>
<title>hello.world.animate()</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
    type="text/javascript"></script>
<style type="text/css">
#coolDiv {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
    background-color: #ccc;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
    // this way works fine for Firefox, but 
    // Chrome and Safari can't do it.
    $("#coolDiv").animate({'left':0}, "slow");
    // So basically if you *start* with a right position
    // then stick to animating to another right position
    // to do that, get the window width minus the width of your div:
$("#coolDiv").animate({'right':($('body').innerWidth()-$('#coolDiv').width())}, 'slow');
    // sorry that's so ugly!
});
</script>
</head>
<body>
    <div style="" id="coolDiv">HELLO</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

原答案:

你有:

$("#coolDiv").animate({"left":"0px", "slow");
Run Code Online (Sandbox Code Playgroud)

更正:

$("#coolDiv").animate({"left":"0px"}, "slow");
Run Code Online (Sandbox Code Playgroud)

文档:http://api.jquery.com/animate/