如何用原生JavaScript实现JQuery版元素90度步进旋转动画?
Vanilla JavaScript Solution for Rotation Animation
Absolutely! You can replicate that smooth rotation animation exactly using vanilla JavaScript—no jQuery required. Let's walk through the complete implementation that matches the behavior of your original example:
Full Implementation
HTML
<button id="rotate">Rotate</button> <div id="div1" style="width: 100px; height: 100px; background: red; margin: 20px;"></div>
JavaScript
let angle = 0; const rotateBtn = document.getElementById('rotate'); const div1 = document.getElementById('div1'); let animationQueue = []; let isAnimating = false; // Handles processing queued animation tasks function processQueue() { if (isAnimating || animationQueue.length === 0) return; isAnimating = true; const targetAngle = animationQueue.shift(); const startAngle = angle - 90; // Match the starting angle before the last click const startTime = performance.now(); const duration = 3000; // 3-second duration, same as original jQuery code function updateRotation(currentTime) { const elapsed = currentTime - startTime; const progress = Math.min(elapsed / duration, 1); // Linear easing (matches jQuery's 'linear') // Calculate the current rotation angle based on animation progress const currentAngle = startAngle + (targetAngle - startAngle) * progress; // Apply rotation with cross-browser compatibility div1.style.transform = `rotate(${currentAngle}deg)`; div1.style.webkitTransform = `rotate(${currentAngle}deg)`; div1.style.mozTransform = `rotate(${currentAngle}deg)`; if (progress < 1) { // Keep updating until the animation completes requestAnimationFrame(updateRotation); } else { // Mark animation as done and process the next queued task isAnimating = false; processQueue(); } } requestAnimationFrame(updateRotation); } // Attach click handler to the rotate button rotateBtn.addEventListener('click', () => { angle += 90; animationQueue.push(angle); processQueue(); });
Key Details That Match the Original jQuery Behavior
- Animation Queuing: Just like jQuery's
animate()method, we use a queue to ensure multiple clicks trigger sequential rotations instead of immediate jumps. This means if you click 3 times quickly, the element will rotate 90 degrees three times in a row, each taking 3 seconds. - Smooth Frame Updates: We use
requestAnimationFrameto sync our animation with the browser's refresh rate, ensuring smooth movement (same as how jQuery handles animation steps). - Linear Easing: The progress calculation uses a linear formula, which matches the
'linear'easing option in your original code—no acceleration or deceleration during the rotation. - Cross-Browser Support: We include prefixed
transformproperties to support older WebKit and Mozilla browsers, just like the original jQuery implementation.
内容的提问来源于stack exchange,提问作者user1525612
相关产品推荐
相关产品推荐

