JQuery动画背景图像在Y轴上

我似乎遇到了JQuery动画的问题。 我可以在正方向上为背景图像设置动画,但不能在负方向上设置动画。 关于如何解决这个问题的任何建议?

$(this).parent().css('background-position-y', '19px'); $(this).parent().animate({ 'background-position-y': '-=19px' }, 1000, 'linear'); 

通过单独的background-position-x/y是Internet Explorer引入但从未将其变为W3C规范的function。 从那以后,任何将其添加到规范的建议都被拒绝了。

请参阅: http : //snook.ca/archives/html_and_css/background-position-xy

你可以随时创建自己的小插件,这并不难。

使用jQuery 1.8,我们现在可以访问$ .Animation方法,它直接为我们提供动画值,而不需要太多工作,所以我们可以这样做:

 $.fn.animateBG = function(x, y, speed) { var pos = this.css('background-position').split(' '); this.x = pos[0] || 0, this.y = pos[1] || 0; $.Animation( this, { x: x, y: y }, { duration: speed }).progress(function(e) { this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px'); }); return this; } 

然后使用它我们可以做:

 $("#background").animateBG(x-value, y-value, speed);​ 

小提琴

这是我几天前为另一个答案掀起的,只适用于像素并且有一些限制,但它很简单,适用于大多数情况。

我想像这样的东西会做你想要的:

 $(this).parent() .css('background-position', '0 19px'); .animateBG(0, 0, 1000);​ 

@adeneo:此解决方案仅在您设置时有效

 this.x = pos[0].split('px')[0] || 0; this.y = pos[1].split('px')[0] || 0; 

否则,起始位置将设置为零。