Animating back to the original position with jQuery
I want to animate the image which is clicked by the user to the top left 100x100 then I want it to return to its original position where the animation started but with this piece of code it keeps sliding by some pixels to the top and left. I couldn't figure out what causes this problem. How can I make it return to its original position?
var posLeft;开发者_C百科
var posTop;
$(this).children("img").click(function() {
goToTopLeft($(this));
$.each($(this).parent().children("img"), function() {
$(this).css("z-index","0");
});
goToFrontFromTopLeft($(this));
$(this).css("z-index", "1");
});
function goToTopLeft(img) {
posLeft = img.position().left;
posTop = img.position().top;
img.animate({ top: '-=100', left: '-=100', height: 'toggle' }, 500);
}
function goToFrontFromTopLeft(img) {
img.animate({ top: posTop, left: posLeft, height: 'toggle' }, 500);
}
While I'm animating from, and to, a different position than yourself, the following code should give you an idea how to do what you're trying to do:
$('img').click(
function(){
var offset = $(this).offset();
var originLeft = offset.left;
var originTop = offset.top;
$(this).animate(
{
'top' : '400px',
'left': '200px'
}, 1500, function() {
$(this).animate({
'top': originTop,
'left' : originLeft
}, 1500)
});
});
Link to JS Fiddle Demo.
I'll note that, in my first attempt, my own animation also had a momentary flicker which seems to be due to the container element having a padding, or margin, which is why the CSS pane on that page contains the following:
body, div, iframe {
padding: 0;
margin: 0;
}
This seems to have cured that momentary 'flicker,' and, I suspect, would likely cure your own issue. But without seeing a live demo it's incredibly hard to know what the problem is, besides guessing. If this doesn't help I'd certainly recommend posting a JS Fiddle, or JS Bin, demo so that we can see what you're working with.
Could it be that the img
you're animating is positioned absolutely? I was able to reproduce this issue with an absolutely positioned img
. If you position the image relatively, I believe this will fix your problem. I set up a simplified example here. Try changing the CSS to position:absolute
and you'll see the issue.
I'm not sure why jQuery won't respect the inline style of the element in combination with the toggle
option for height, maybe others can chime in about that.
This function returns all animated styles to starter position/style
var animate = function(selector, obj) {
var original = {};
if (!$(selector).is(":animated")) {
$.each(obj, function(i, v) {
original[i] = $(selector).css(i);
});
$(selector).animate(obj, function() {
$(selector).animate(original);
})
}
}
精彩评论