Jquery animate from relative to absolute position? Possible?
I am trying to animate a couple of images across a screen. Ideally I would like the images to start out centered in the browser window (whatever its size) and have them move over to a an exact position (say 100px from top, 100px from left) of the browser window. My animation works fine, but only relative to the starting location. I can't figure out how to get it to move to an specific position without making the starting point fixed (which obviously defeats the centering idea).
Here is the code I am working with at the moment:
$('img#one').delay(300).animate({left: '-=485', top: '-=448'},500);
$('img#two').delay(800).animate({left: '-=645', top: '-=399'},800);
$('img#dash').delay(800).animate({left:'-=1398'},800);
Here is the HTML:
<div id="logowrap"><img id="one" src="images/one.png"><img id="two" src="images/two.png"></div>
<img开发者_开发知识库 id="dash" src="images/dash.png">
</div>
And here is the CSS:
#one {
margin-top: 500px;
margin-left: 530px;
position: relative;
display: block;
z-index: 6;
}
#dash {
display: block;
z-index: 8;
margin-left: 1600px;
margin-top: -505px;
position: relative;
}
body {
margin: 0;
width: 100%;
}
#two {
margin-left: 698px;
position: relative;
display: block;
z-index: 14;
margin-top: -53px;
}
Any help highly appreciated! Thanks!
You could try appending the element's absolute position using the .offset()
method -- http://api.jquery.com/offset/ -- with that you could animate the image at 0,0 at document level, and then append e.g. 100 left and 100 top to get it absolute at 100,100 from the documents 0,0 position (sorry, it's late but I hope you understand my ramblings).
Thanks to Peol, I just figured it out, with his answers leading me in the right direction. FWIW, here is my final code:
$(document).ready(function(){
var offsetg = $('img#one').offset();
offsetgmoveL = offsetg.left - 42;
offsetgmoveT = offsetg.top + 282;
var offsetM = $('img#two').offset();
offsetMmoveL = offsetM.left +115;
offsetMmoveT = offsetM.top + 232;
$('img#one').delay(300).animate({left: '-=' + offsetgmoveL + '', top: '-=' + offsetgmoveT + ''},500);
$('img#two').delay(800).animate({left: '-=' + offsetMmoveL + '', top: '-=' + offsetMmoveT + ''},300);
精彩评论