2010-04-23 171 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));