jQuery .animate()不接受变量

时间:2014-05-14 13:48:03

标签: javascript jquery

我正在尝试在jQuery animate()中使用变量,但它无效。我不想两次使用相同的代码,所以有没有办法更好地做到这一点?

代码:

var direction = 'scrollTop';
// var direction = 'scrollLeft';

var value = 2000;// changes everytime

$('html, body').animate({direction: value}, 1000, function(){
    // more code here
});

1 个答案:

答案 0 :(得分:11)

您可以使用:

var direction = 'scrollTop';
// var direction = 'scrollLeft';

var value = 2000;// changes everytime

var opts = {};
opts[direction] = value;

$('html, body').animate(opts,1000,function(){
    // more code here
});