I want to use Element.animate() with the properties I want to animate as variables.But it seems that it doesn't work.
var pr="marginLeft"
document.getElementById("someId").animate([
{ pr:'0px' },
{ pr:'50px' },
],{
duration:1000,
fill:'forwards'
});
What can I do if I really need to use a variable instead of a property?
You can create an object with the properties that you need, set the values using obj[X] = Y
, and use this object as the parameter for your animate
function:
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>
You can use ES2015 computed property names.
let pr='marginLeft';
document.getElementById('someId').animate(
[
{ [pr]: '0px' },
{ [pr]: '50px' },
],
{ duration:1000, fill:'forwards' }
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.