jquery animate background-position - problem getting the current background position first
I am trying to animat开发者_高级运维e the background of an element from it's current position when the user clicks a button. I am able to do this on the first click but the subsequent clicks fail.
Here's my code...
var testme;
$(document).ready(function(){
$(".navleft").live("click", function() {
testme = parseInt($(this).css("background-position").replace("% 0%", "").replace("px 0%", ""));
$(this).parent().animate({backgroundPosition: (testme + 297) + "px"}, 500);
$(this).parent().find("p").text(testme);
});
});
EDIT:
$(".navleft").live("click", function() {
$(this).parent().animate({backgroundPosition: "+=297"}, 500);
});
As suggested below, this works great unless you're using IE where it resets back to 0 at each click then animates again.
Here's a link to what I mean... http://jsfiddle.net/TdaSV/
Solution (as a result of being pushed in the right direction):
$(".navleft").live("click", function() {
$(this).parent().animate({'background-position-x': '+=297'}, 500);
});
You should first stop the previous animation and then start a new one:
$(this).parent().stop(true, true).animate({backgroundPosition:...
also if you need to add 297 pixels to the current background position, you don't need to read the current position, following shoudl work:
$(this).parent().animate({backgroundPosition: "+=297"}, 500);
see more examples in jquery website.
精彩评论