2016-02-03 193 views
0

可以说我有以下功能jQuery的动画向左或向右变

function slide(element, direction, hide){ 
    if (direction == "left") { 
     $(element).animate({ 
      "left": 500, 
     }, 500, function(){ 
      if(hide) { 
       $(element).css("display", "none"); 
      } 
     }); 
    } else { 
     $(element).animate({ 
      "right": 500, 
     }, 500, function(){ 
      if(hide) { 
       $(element).css("display", "none"); 
      } 
     }); 
    } 
} 

其本身的伟大工程。但我想消除的if else词来得到这样的

function slide(element, direction, hide){ 
    $(element).animate({ 
     direction : 500, 
    }, 500, function(){ 
     if(hide) { 
      $(element).css("display", "none"); 
     } 
    }); 
} 

这在所有的不工作......有什么办法权在animate函数变量来控制左/?

+0

在'方向:500'中,变量不会被分析。 – Tushar

+1

http://stackoverflow.com/questions/882727/is-there-a-way-that-use-var-to-create-json-objects-with-a-key –

回答

1

用方向自己创建一个对象,然后在动画函数中使用它,如下所示。

function slide(element, direction, hide) { 
    var obj = {}; 
    obj[direction] = 500; 

    $(element).animate(obj, 500, function() { 
     if (hide) { 
      $(element).css("display", "none"); 
     } 
    }); 
}