2012-10-30 134 views
1

我爲wordpress主題的側欄小部件創建了切換下拉效果。使用jQuery爲多個背景位置設置動畫效果

h2小工具內的標籤有兩個不同背景位置的背景圖像。

的CSS這個背景是這樣的:

background-image: url(images/h2bg.png), url(images/button.png); 
background-position: center left, bottom right; 
background-repeat: no-repeat,no-repeat; 

我想要做的是動畫第一背景(h2bg.png)從元素框,當用戶點擊h2元素上,然後將第二個背景圖像的位置更改爲top left。 (這是一個很小的精靈圖像)

我的jQuery腳本是這樣的:(你不需要去通過它)

$(document).ready(function() { 
    $('#sidebar div.widget').each(function(i) { 
     height = $(this).css('height'); 
     $(this).attr('data-height',height); 
     $(this).attr('data-animate','ON'); 
    }); 
    $('.widget h2').click(function() { 
     if ($(this).parent('div.widget').attr('data-animate') == 'OFF') { 
      $(this).parent('div.widget').attr('data-animate','ON'); 
      height = $(this).parent('div.widget').attr('data-height'); 
      $(this).parent('div.widget').animate({ 
       height: height 
      },500); 
      $(this).animate({ 
       'background-position-x': '0%, 100%' 
      },500,function() { 
       $(this).css('background-position-y','50%, 100%'); 
      }); 
     } else { 
      $(this).parent('div.widget').attr('data-animate','OFF'); 
      $(this).parent('div.widget').animate({ 
       height: '29px' 
      },500); 
      $(this).animate({ 
       'background-position-x': '-100%, 100%' 
      },500,function() { 
       $(this).css('background-position-y','50%, 0%'); 
      }); 
     } 
    }); 
}); 

長話短說。我注意Java返回background-position-xbackground-position-y作爲percenatges之間用分號分隔。

所以我在動畫中使用的百分比,它對一個背景圖像工作正常。但是當涉及到多個背景時,它不起作用!我用分號嘗試它...沒有分號和像素值,但沒有運氣!

我該如何處理jQuery的多個背景位置屬性?

回答

0

只需使用'background-position' : 'value px value px''left top'或任何適合您的東西。

+0

你可以舉一個如何使用這些屬性的例子嗎?它會幫助那些不熟悉jQuery的人。 – KLee1

1

您可能需要重新定義.css/.animate方法中的圖像URL。

'background-image' : 'url("image1.png"), url("image2.png")', 
'background-position' : 'right 50px left 50px' (or whatever) 

CSS使用圖像-URL聲明的順序,以確定哪些屬性適用於哪個圖像,所以它可以是僅僅是不具有參考點的瀏覽器(由於被內聯應用的樣式的情況下而不是在樣式表中)。

此外,堅持'背景位置'聲明。不確定background-position-x,background-position-y是否適用於多個圖像。

更新

jQuery無法爲背景圖像設置動畫效果。爲了獲得相同的效果,您必須使用目標元素下的堆疊div來僞造,然後重新調整它們的大小。

+0

刪除分號會破壞整個事物,並且使用'backgournd-positiond'而不是'-x'和'-y'也不起作用。沒有動畫這個代碼的作品完美:'background-position',' - 150px 0px,255px 0px'但是當我在'animate'函數中使用它時,它什麼也沒做。 – Nojan

+1

經過一點研究,看起來好像jQuery不能實際上訪問必要的屬性以允許對背景圖像屬性進行「動畫處理」。我會繼續尋找。 – monners

+0

錯誤。 jquery可以動畫一個背景圖像的位置!例如:'$('#element')。animate({'background-position-x':'+ = 400px'},400);'我不知道如何在同一個元素上動畫兩個背景圖片... – ProblemsOfSumit