jQuery .animate()不接受变量

use*_*235 -1 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
});
Run Code Online (Sandbox Code Playgroud)

A. *_*lff 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
});
Run Code Online (Sandbox Code Playgroud)

  • @Cerbrus`direction`是一个变量 (2认同)