2013-03-23 34 views
0

我正在嘗試使用jQuery的.animate()方法爲元素的背景位置設置動畫。背景位置屬性是通過定義x和y的值,像這樣設置:jQuery .animate()具有多個值的單個CSS屬性

background-position: 100px 100px; 

的Webkit現在支持background-position-xbackground-position-y,但它尚未在Firefox支持。如果我只動畫一個值 -

例如。 $(div).animate({'background-position':'200px'}, 1000); - 它會自動爲X值設置動畫而不是方式。我無法找到一種方法來獨立地爲Y值設置動畫。

這是一個讓語法正確的問題嗎?一些串聯的技巧?

注意:我確實使用background-position-y在webkit中工作,但也希望獲得FF支持。

+0

我認爲這個問題已經在這裏找到答案:http://stackoverflow.com/questions/5171080/jquery-animate-background-position – 2013-03-23 17:21:45

+0

感謝@AndreaCasaccia! – KeenanC 2013-03-23 18:05:47

回答

0

只需使用以下命令:

background-position:0 200px; 

其中0是x和200是Y:

background-position:x y; 
+0

動畫中的多個值似乎不起作用:http://jsfiddle.net/qhqnd/似乎在上面的註釋中鏈接的問題中有解釋 – 2013-03-23 17:23:05

0

我相信這需要一個jQuery的擴展。這是一個有點笨重,但here's a working example

/** 
* @author Alexander Farkas 
* v. 1.02 
* 
* Edited by Nelson Wells for jQuery 1.8 compatibility 
*/ 
(function($) { 
    $.extend($.fx.step,{ 
     backgroundPosition: function(fx) { 
      if (fx.pos === 0 && typeof fx.end == 'string') { 
       var start = $.css(fx.elem,'backgroundPosition'); 
       start = toArray(start); 
       fx.start = [start[0],start[2]]; 
       var end = toArray(fx.end); 
       fx.end = [end[0],end[2]]; 
       fx.unit = [end[1],end[3]]; 
      } 
      var nowPosX = []; 
      nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0]; 
      nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1]; 
      fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1]; 

      function toArray(strg){ 
       strg = strg.replace(/left|top/g,'0px'); 
       strg = strg.replace(/right|bottom/g,'100%'); 
       strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2"); 
       var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/); 
       return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]]; 
      } 
     } 
    }); 
})(jQuery); 

$('.test').animate({ 
    'background-position-x': '100px', 
    'background-position-y': '200px', 
    backgroundPosition:"+100px 200px" 
}, 400, 'linear');