requestAnimationFrame 兼容方案
阿新 • • 發佈:2019-01-21
lin eight cli func window can 點擊 inner http
目錄
- html代碼
- css代碼
- JavaScript代碼
編寫涉及:css, html, js
在線演示codepen
html代碼
<div class="roll-box">
<div class="inner-box">move</div>
</div>
<button onclick="startMove()"> start move</button>
css代碼
.roll-box { position: relative; width: 600px; height: 400px; background: #007acc; overflow: hidden; color: #fff; } .inner-box { position: absolute; top: 10px; left: 0; width: 50px; height: 50px; text-align: center; line-height: 50px; background-color: rgb(245, 152, 30); } button{ margin-top: 20px; padding: 6px 10px; border: 0; color: #fff; background-color: rgb(39, 133, 240); }
JavaScript代碼
let moveCount = 0; let rafId = ‘‘; const ele = document.querySelector(‘.inner-box‘); window.requestAniFrame = (function () { return window.requestAnimationFrame // Older versions Chrome/Webkit window.webkitRequestAnimationFrame || // Firefox < 23 window.mozRequestAnimationFrame || // opera window.oRequestAnimationFrame || // ie window.msRequestAnimationFrame || function (callback) { return window.setTimeout(callback, 1000 / 60); }; })() window.cancelAnimation = (function () { return window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.cancelRequestAnimationFrame || function (id) { clearTimeout(id) } })() function moveFn() { ele.setAttribute(‘style‘, ‘left:‘ + moveCount + ‘px‘); moveCount++ if (moveCount > 550) { window.cancelAnimation(rafId) } else { rafId = window.requestAniFrame(moveFn) } } function startMove() { // 必須先清除,否者多次點擊會生成多個動畫幀,導致元素移動速度加快 window.cancelAnimation(rafId) rafId = window.requestAniFrame(moveFn) }
若有疑問或錯誤,請留言,謝謝!Github blog issues
requestAnimationFrame 兼容方案