我有一个根据 0 到 3 之间的值旋转的元素。 旋转有一个过渡,它总是应该顺时针旋转。 如果最大值溢出,该值将设置为最小值,但复位时的转换将逆时针旋转。
我的想法是将值设置为 -1 并禁用转换。 在一帧动画之后,启用过渡并将值设置为 0,因此它将顺时针旋转。
requestAnimationFrame 不起作用,但 0 毫秒的 setTimeout 起作用。 requestAnimationFrame 和 setTimeout 有什么区别?
function rotateAnimation(){
let cb = rotate();
cb && window.requestAnimationFrame(cb);
}
function rotateTimeout(){
let cb = rotate();
cb && window.setTimeout(cb,0);
}
function rotate(){
let rotate = document.querySelector(".rotate");
let value = ++rotate.dataset.value % 4;
let cb = null;
if(value === 0){
rotate.style.setProperty("transition", "none");
value = -1;
cb = () => {
rotate.style.removeProperty("transition");
rotate.style.setProperty("--value", "0");
};
}
rotate.style.setProperty("--value", value);
return cb;
}
.rotate {
display: inline-block;
transition: transform 0.2s linear;
transform: rotate(calc(var(--value, 0) * 90deg));
}
<div class="rotate" data-value="0">Rotate</div>
<button onclick="rotateAnimation()">rotate - reset by animation frame</button>
<button onclick="rotateTimeout()">rotate - reset by timeout</button>