JSFiddle - React, Tailwind, and code Playground
HTML
<div id="anim"> Click here to start animation</div>
CSS
#anim {
position: absolute;
left: 0px;
width: 150px;
height: 150px;
line-height: 150px;
background: aqua;
color: white;
border-radius: 10px;
padding: 1em;
}
JavaScript
// 兼容性处理
window.requestAnimFrame = (function() {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60)
}
)
})()
var elem = document.getElementById('anim')
var startTime = undefined
function render(time) {
time = Date.now()
if (startTime === undefined) {
startTime = time
}
elem.style.left = ((time - startTime) / 10) % 300 + 'px'
elem.style.top = ((time - startTime) / 10) % 300 + 'px'
elem.style.borderRadius = ((time - startTime) / 10) % 300 + 'px'
elem.style.opacity = Math.floor((time - startTime / 100)) % 2 === 0 ? 1 : 0.3
}
elem.onclick = function() {
(function animloop() {
render()
requestAnimFrame(animloop, elem)
})()
}