繁体   English   中英

如何使用Javascript设置动画的持续时间?

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

我希望JavaScript函数花费我提供的时间来执行。 我知道setTimeOut()setInterval()作用,我不是在寻找它们。

例如,我的div top: 0left: 0 我希望我的JS函数在给定的时间内将div left: 0left: 50

请提供原始的JavaScript解决方案,而不是jQuery。

Web动画定义了实验性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> 

我相信这就是您要寻找的,没有jQuery要求。

编辑:我根据以下评论起草了一个新版本。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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