如何实现用户进入页面时幸运转盘自动旋转?
实现幸运转盘页面加载时自动旋转的方案
要让转盘在用户进入页面时自动旋转,最简洁的方式是把旋转逻辑封装成独立函数,既供点击按钮调用,也在页面初始化时直接执行。
修改后的JavaScript代码
// Immediately invoked function expression // to not pollute the global scope (function () { const wheel = document.querySelector('.wheel'); const startButton = document.querySelector('.button'); let deg = 0; // 封装旋转逻辑为独立函数 function spinWheel() { // Disable button during spin startButton.style.pointerEvents = 'none'; // Calculate a new rotation between 5000 and 10 000 deg = Math.floor(5000 + Math.random() * 5000); // Set the transition on the wheel wheel.style.transition = 'all 10s ease-out'; // Rotate the wheel wheel.style.transform = `rotate(${deg}deg)`; // Apply the blur wheel.classList.add('blur'); } // 按钮点击触发旋转 startButton.addEventListener('click', spinWheel); // 页面加载完成后自动触发旋转 spinWheel(); wheel.addEventListener('transitionend', () => { // Remove blur wheel.classList.remove('blur'); // Enable button when spin is over startButton.style.pointerEvents = 'auto'; // Need to set transition to none as we want to rotate instantly wheel.style.transition = 'none'; // Calculate degree on a 360 degree basis to get the "natural" real rotation // Important because we want to start the next spin from that one // Use modulus to get the rest value from 360 const actualDeg = deg % 360; // Set the real rotation instantly without animation wheel.style.transform = `rotate(${actualDeg}deg)`; }); })();
修改说明
- 把原来点击事件里的旋转代码抽成了
spinWheel函数,避免重复编写逻辑 - 在IIFE的最后直接调用
spinWheel(),这样页面加载完成后会自动触发转盘旋转 - 按钮的点击事件依然绑定
spinWheel函数,保留原有的手动触发旋转功能
HTML部分无需修改,保持原有结构即可。
内容的提问来源于stack exchange,提问作者Misha
相关产品推荐
相关产品推荐

