简体   繁体   中英

How do I set the time duration of an animation using Javascript?

I want a JavaScript function to take the time I provide to execute. I know what setTimeOut() or setInterval() does, I am not looking for them.

For example, I have a div at top: 0 and left: 0 . I want my JS function to take the div from left: 0 to left: 50 in the given time.

Please provide a raw JavaScript solution, not jQuery.

Web Animations defines the experimental Element.animate

 document.getElementById("test").animate([ { left: '0px' }, { left: '50px' } ], { duration: 1000, fill: 'forwards' }); 
 #test { background-color: green; width: 100px; height: 100px; position: relative; } 
 <div id="test"></div> 

 var timeInMs = 500; document.getElementById("test").style.transition = "all "+timeInMs+"ms"; 
 #test { background-color: green; width: 200px; height: 150px; margin-left: 0; } 
 <div id='test' onclick="this.style.marginLeft = '50px';"></div> 

I believe that this is what you are looking for, with no jQuery requirements.

EDIT: I have drafted a new version based on the comments below.

 var timeInMs = 500; document.querySelectorAll("#test *").forEach(function(a){ a.style.transition = "all "+timeInMs+"ms"; a.addEventListener("click",function(){ this.style.margin = 0; this.style.opacity = 0; this.style.width = 0; }); }); 
 #test * { background-color: green; width: 200px; height: 150px; margin: 10px; display: inline-block; } #test { background-color: lightblue; display: inline-block; } 
 <div id="test"> <div></div><div></div><div></div> </div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM