为何For Loop不等待setTimeout?页面深色模式平滑过渡遇阻
解决深色模式平滑过渡的问题
你的代码核心问题是:for循环会瞬间执行完所有迭代,所有setTimeout都会在100ms后同时触发,导致颜色直接跳变,无法实现逐步过渡的效果。
下面提供两种可行的解决方案:
方案一:使用setInterval定时器
if (!localStorage.getItem('theme')){ localStorage.setItem('theme', 'light') } function changeColor(){ let theme = localStorage.getItem('theme'); let currentValue = theme === 'dark' ? 30 : 255; const targetValue = theme === 'dark' ? 255 : 30; const step = theme === 'dark' ? 1 : -1; // 先更新本地存储的主题状态 localStorage.setItem('theme', theme === 'dark' ? 'light' : 'dark'); const interval = setInterval(() => { currentValue += step; document.body.style.backgroundColor = `rgb(${currentValue}, ${currentValue}, ${currentValue})`; // 到达目标值后停止定时器,确保最终颜色准确 if ((step > 0 && currentValue >= targetValue) || (step < 0 && currentValue <= targetValue)) { clearInterval(interval); document.body.style.backgroundColor = `rgb(${targetValue}, ${targetValue}, ${targetValue})`; } }, 100); }
方案二:使用递归setTimeout
if (!localStorage.getItem('theme')){ localStorage.setItem('theme', 'light') } function changeColor(){ let theme = localStorage.getItem('theme'); let currentValue = theme === 'dark' ? 30 : 255; const targetValue = theme === 'dark' ? 255 : 30; const step = theme === 'dark' ? 1 : -1; localStorage.setItem('theme', theme === 'dark' ? 'light' : 'dark'); function updateColor() { currentValue += step; document.body.style.backgroundColor = `rgb(${currentValue}, ${currentValue}, ${currentValue})`; // 未到达目标值时,继续调度下一次更新 if ((step > 0 && currentValue < targetValue) || (step < 0 && currentValue > targetValue)) { setTimeout(updateColor, 100); } else { document.body.style.backgroundColor = `rgb(${targetValue}, ${targetValue}, ${targetValue})`; } } // 启动首次颜色更新 updateColor(); }
这两种方法都会逐个执行颜色更新操作,每次只调度一次延迟任务,从而实现RGB值逐步±1的平滑过渡效果。
内容的提问来源于stack exchange,提问作者npxr c
相关产品推荐
相关产品推荐

