You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复CSS实现的幻灯片图片淡入淡出切换时画面泛白的问题

问题根因

泛白问题来自两个核心逻辑缺陷:

  1. 交叉淡入阶段两张图片同时处于半透明状态,alpha叠加后会透出底层白色背景,导致整体亮度升高出现泛白
  2. 未做切换频率限制,快速按键会打断未完成的过渡,造成多张图片同时半透明叠加,进一步放大泛白问题

修复方案

只需少量修改CSS和JS逻辑即可解决,核心思路是让过渡阶段仅上层旧图片执行透明度变化,下层新图片直接完全显示挡住背景,避免双半透叠加:

修改CSS代码

* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body, figure {
  margin: 0;
  padding: 0;
}

body {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.slideshow {
  height: 600px;
  width: 800px;
  max-width: 100%;
  display: flex;
  align-items: center;
  position: relative;
}

img {
  width: 100%;
  position: absolute;
  opacity: 0;
  /* 非过渡阶段默认关闭过渡效果 */
  transition: none;
  z-index: 2;
}

.visible {
  opacity: 1;
  z-index: 3;
}

/* 仅给需要淡出的元素添加过渡 */
.fading-out {
  transition: opacity .3s ease;
  opacity: 0;
  z-index: 4;
}

修改JS代码

const imgs = document.querySelectorAll('img');
const imgCount = imgs.length - 1;
let index = 0;
// 切换锁,避免动画未完成就触发下一次切换
let isSwitching = false;
imgs[index].classList.add('visible');

window.addEventListener('keydown', () => {
  if (isSwitching) return;
  isSwitching = true;

  const oldIndex = index;
  index = index === imgCount ? 0 : ++index;

  // 旧元素添加淡出类,上层执行淡出动画
  imgs[oldIndex].classList.add('fading-out');
  // 新元素直接设为可见,放在下层完全显示挡住背景
  imgs[index].classList.add('visible');

  // 过渡完成后清理旧元素的类,重置切换锁
  setTimeout(() => {
    imgs[oldIndex].classList.remove('visible', 'fading-out');
    isSwitching = false;
  }, 300); // 时长和CSS中过渡时间保持一致即可
});

可选优化

如果希望过渡效果更柔和,可以调整.fading-out中的transition-timing-function为ease-in-out,或者适当拉长过渡时长到0.4-0.5s。


内容的提问来源于stack exchange,提问作者Junitar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:54:04