2012-01-18 34 views
2

我需要使用jQuery为元素的background-position属性设置动画效果。按照本教程,使用默认的jQuery动画功能,我没有运气。自定义“动画”jQuery功能。如何重置步骤的“现在”变量?

http://snook.ca/archives/javascript/jquery-bg-image-animations

我的作用是这样的:

$('#content').css({backgroundPosition: "0 0"}) 
      .animate(
       {backgroundPosition:"(0 -900px)"}, 
       {duration:500} 
      ); 

我没有运气,所以我尝试编写我自己的函数,改变一个元素的垂直背景位置。它看起来像:

$.fn.moveBackgroundY = function(pixels, duration, easing) { 

    return this.animate(
       { pixels: pixels }, 
       { 
        step: function(now,fx) { 

         console.log("Background Y position - " + now); 

         $(this).css({ 
          backgroundPosition: '0px ' + now + 'px', 
         }); 
        }, 
        duration: duration, 
        complete: function() { 
         $(this).css({ 
          backgroundPosition: '0px 0px', 
         }); 
        } 
       }, easing); 
}; 

设置动画元素的Y背景位置-900,我这样调用该函数:

$('#content').moveBackgroundY(-900, 2100, 'easeInOutCubic'); 

请注意,这里的变量现在(后台位置Y)内步骤:将从0减少到-900。

这工作正常,但这里来了我的问题。在此之后,我需要重置此背景位置“0像素0像素”直接与jQuery的的.css()函数,然后再制作动画,如:

$('#content').moveBackgroundY(300, 2100, 'easeInOutCubic'); 

在这种情况下,我reseted我的背景位置“0px 0px”,参数现在应该从0到300,但它从-900到300,其中-900是我第一次调用我的函数设置的值。

任何人都知道什么是错的,或者我该如何重置此参数以便每次都采用正确的值?

我有另一个像它这样的旋转元素改变CSS3属性转换 - 旋转,我有同样的问题。

感谢您的帮助!

回答

3

这为我工作:

return this.animate(
      { pixels: pixels }, 
      { 
       step: function(now,fx) { 
        var calculatedPixels = this.pixels; 
        console.log("Background Y position - " + now); 


        $(this).css({ 
         backgroundPosition: '0px ' + calculatedPixels + 'px', 
        }); 
       }, 
       duration: duration, 
       complete: function() { 
        $(this).css({ 
         backgroundPosition: '0px 0px', 
        }); 
        //not so sure about this but you have to do this somehow 
        this.pixels = 0; 
       } 
      }, easing); 

位置复位的问题来自于一个事实,你是动画“像素”值不backgroundPosition。 然后,您将“像素”值应用于backgroundPosition。 然后重置backgroundPosition,但不重置“像素”值。 下一个动画会将最新的像素值作为起始值。 你必须找到一种方法,以某种方式将“像素”值重置为backgroundPosition值,以使它们保持同步。