Element.animate() 变量为 属性 来制作动画

Element.animate() with variable as property to animate

我想将 Element.animate() 与我想要设置动画的属性一起使用,因为 variables.But 似乎它不起作用。

var pr="marginLeft"
document.getElementById("someId").animate([
  { pr:'0px' },
  { pr:'50px' },
],{
  duration:1000,
  fill:'forwards'
});

如果我真的需要使用变量而不是 属性,我该怎么办?

您可以创建一个具有所需属性的对象,使用 obj[X] = Y 设置值,并将此对象用作 animate 函数的参数:

var pr="marginLeft";
var animationProperties = {
  duration: 1000,
  fill:'forwards'
}

// Here I added the `marginLeft` to the object:
animationProperties[pr] = '50px';

$('#someId').animate(animationProperties)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="someId">asd</div>

您可以使用 ES2015 计算的 属性 名称。

let pr='marginLeft';

document.getElementById('someId').animate(
  [
    { [pr]: '0px' },
    { [pr]: '50px' },
  ],
  { duration:1000, fill:'forwards' }
);