实现浏览器在每一帧中,将页面div元素的宽度变长1px,直到宽度达到100px后停止。
我们采用requestAnimationFrame来实现这个功能,关键代码如下:
<div id="div" className={"progress-bar "} style={{ backgroundColor: 'pink' }}>
</div>
<button id="start">开始动画</button ><script>const btn = document.getElementById('start');const div = document.getElementById('div');let start = 0;const allInterval = [];const progress = () => {div.style.width = div.offsetWidth + 1 + 'px'div.innerHTML = (div.offsetWidth) + '%'if (div.offsetWidth < 100) {const current = Date.now()allInterval.push(current - start)start = currentrequestAnimationFrame(progress)} else {console.log(allInterval) // 打印requestAnimationFrame的全部时间间隔}}btn.addEventListener('click', () => {div.style.width = 0const currrent = Date.now()start = currrentrequestAnimationFrame(progress)console.log(allInterval)})</script>
最终的效果如下: