2010-04-23 170 views
4

這似乎是一個簡單的事情,但我沒有太大的成功。我只是實現一個簡單的動畫,使用animate()向左或向上移動div,但我希望能夠動態設置「頂部」和「左側」CSS屬性。我想使用相同的功能,而不是必須有兩個,一個用於「左」,一個用於「頂」。動態選擇動畫中的css屬性

下面是一些給出這個想法的代碼。

 

function test($element){ 
    $element.click(function(){ 
     var cssProperty; 
     var direction = "left"; 
     var moveTo = "100px"; 

     if (direction === "top") { 
      cssProperty = "top"; 
     } else { 
      cssProperty = "left"; 
     } 

     /*Using variable as CSS property - This doesn't work */ 
     $(this).animate({ 
      cssProperty: moveTo 
     }, 1000); 

     /*Using variable as the CSS Values - This does */ 
     $(this).animate({ 
      left: moveTo 
     }, 1000); 
    }); 
} 
 

變量在css值端工作,但不在css選擇端。任何人有任何建議?

感謝

回答

3

看到這個:http://www.jibbering.com/faq/faq_notes/square_brackets.html

function test($element){ 
    $element.click(function(){ 
     var cssProperty; 
     var direction = "left"; 
     var moveTo = "100px"; 
     var animationProperties = {}; 

     if (direction === "top") { 
      cssProperty = "top"; 
     } else { 
      cssProperty = "left"; 
     } 

     animationProperties[cssProperty] = moveTo; 

     // This does work. 
     $(this).animate(animationProperties, 1000); 

     // Or else, using computed properties introduced in ES6. 
     $(this).animate({ 
      [cssProperty]: moveTo 
     }, 1000); 
    }); 
} 

Browser supportcomputed properties

+0

謝謝! ...這排序我的問題! – patocallaghan 2010-04-23 11:08:50

+0

你的兩個例子(工作,不工作)有什麼區別?這是相同的代碼行:'$(this).animate(animationProperties,1000);' – krlzlx 2016-03-11 16:43:32

+0

@krlzlx抱歉,可能是複製/粘貼錯誤。不過,我已經更新了答案,現在它包含了一些在2010年不可用的最新進展。 – 2016-03-11 17:47:55

0

「不工作」部分不起作用,因爲您不能使用變量值來聲明JSON中的字段。要解決這個你應該有(更換不工作的部分):

// Create an empty object 
var newStyle = { }; 
// Add a dynamically named field 
newStyle[cssProperty] = moveTo; 
// Start the animation 
$(this).animate(newStyle, 1000); 
+0

謝謝你的回答我的問題!我必須補充說,第一行是不正確的,該變量未定義,所以我只是將其更改爲 var newStyle = {}; 它工作! 再次感謝! – patocallaghan 2010-04-23 11:06:11

+0

哈!真正。 固定它;) – Shtong 2010-04-23 11:08:41

0

我發現這個解決方案很好,但是當我在Internet Explorer測試 - 遺憾的是它沒有工作。拋出錯誤:「預期標識符,字符串或數字Internet Explorer動態屬性」。所以我爲每個條件創建一個動畫調用的不太好的解決方案,確保將隊列設置爲false,因爲它需要同時運行並應用於包含其他動畫的相同元素。例如:

if (directionX == "right"){ 
    $(this).animate({"right": amountX},{duration: 600, queue: false}); 
} else if (directionX == "left"){ 
    $(this).animate({"left": amountX},{duration: 600, queue: false}); 
} 
if (directionY == "top"){ 
    $(this).animate({"top": amountY},{duration: 600, queue: false}); 
} else if (directionY == "bottom"){ 
    $(this).animate({"bottom": amountY},{duration: 600, queue: false}); 
} 
$(this).animate({ 
    "backgroundSize": bigWidths_array[itemNum], 
    "width":   bigWidths_array[itemNum], 
    "height":   bigHeights_array[itemNum]}, 
    600, false, showBigText(itemNum));