如何在JavaScript中使用CSS transition实现渐变背景平滑过渡
背景渐变过渡失效原因
- CSS
transition原生不支持linear-gradient这类background-image属性的过渡动画,这是你之前设置transition不生效的核心原因 - 你编写的
randomNum函数生成的随机数范围为0-17,而颜色数组总长度仅为6,会频繁出现索引越界取到undefined的问题
平滑过渡实现方案
推荐使用伪元素叠加控制透明度的方案,性能最优且无需引入额外依赖:
第一步:添加对应CSS样式
body { position: relative; min-height: 100vh; margin: 0; --before-bg: #fff; --after-bg: #fff; --after-opacity: 0; } body::before, body::after { content: ""; position: absolute; inset: 0; transition: opacity 1s ease; /* 此处1s为过渡时长,可自行调整 */ z-index: -1; } body::before { background: var(--before-bg); } body::after { background: var(--after-bg); opacity: var(--after-opacity); }
第二步:替换为修正后的JS代码
const colors = [ "#ff5e57", "#d2dae2", "#485460", "#ffa801", "#ffd32a", "#ff3f34" ]; const body = document.querySelector("body"); let isBeforeActive = true; // 修正后的随机索引生成函数,返回两个不重复的有效颜色索引 function getTwoRandomIndex() { const len = colors.length; const index1 = Math.floor(Math.random() * len); let index2; do { index2 = Math.floor(Math.random() * len); } while(index2 === index1); return [index1, index2]; } function changeBackground() { const [c1, c2] = getTwoRandomIndex(); const newGradient = `linear-gradient(to right, ${colors[c1]}, ${colors[c2]})`; if (isBeforeActive) { body.style.setProperty('--after-bg', newGradient); body.style.setProperty('--after-opacity', '1'); } else { body.style.setProperty('--before-bg', newGradient); body.style.setProperty('--after-opacity', '0'); } isBeforeActive = !isBeforeActive; } // 初始化背景 const [initC1, initC2] = getTwoRandomIndex(); body.style.setProperty('--before-bg', `linear-gradient(to right, ${colors[initC1]}, ${colors[initC2]})`); setInterval(changeBackground, 2000); // 此处2000为背景切换间隔,单位ms,可自行调整
内容的提问来源于stack exchange,提问作者Seol chan
相关产品推荐
相关产品推荐

