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

如何用mix blend mode或invert filter实现进度条文字反色效果?

实现带动态反色文字的彩色进度条

核心思路是利用mix-blend-mode: difference让文字在不同背景上自动变色,同时修正原代码里的颜色反转和进度计算问题,以下是调整后的完整代码:

完整代码

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="progressBar">
  <div class="bar"></div>
  <div id="timer"></div>
</div>

CSS

#progressBar {
  width: 90%;
  margin: 10px auto;
  height: 120px;
  background-color: #B8C3C3; /* 浅色背景色 */
  position: relative;
}

#progressBar .bar {
  height: 100%;
  width: 0;
  background-color: #4B5863; /* 深色进度条色 */
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
}

#timer {
  text-align: center;
  height: 100%;
  line-height: 120px; /* 垂直居中文字 */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  font-family: "Manrope";
  font-size: 80px;
  font-weight: 800;
  color: white;
  mix-blend-mode: difference; /* 关键:实现文字随背景变色 */
  z-index: 2; /* 确保文字在进度条上方 */
}

JavaScript

// 用短时间参数方便测试,10秒倒计时
progress(10, 10, $('#progressBar'));

function progress(timeleft, timetotal, $element) {
  // 修正进度计算:剩余时间越少,进度条越宽
  var progressBarWidth = ((timetotal - timeleft) / timetotal) * $element.width();
  $element.find('div.bar').animate({ width: progressBarWidth }, 1000, "linear");
  
  if(timeleft > 0) {
    setTimeout(function() {
      progress(timeleft - 1, timetotal, $element);
    }, 1000);
  }
  
  var date = new Date(null);
  date.setSeconds(timeleft);
  var timeString = date.toISOString().substr(11, 8);
  $('#timer').text(timeString);
}

关键修改说明

  • 移除了原代码中#progressBar的filter: invert(100%),避免颜色反转导致的混乱
  • 调整进度条宽度计算逻辑,让进度条随倒计时从左到右延伸,匹配你要的“进度条在数字后方移动”的效果
  • 用line-height实现文字垂直居中,比手动top定位更精准
  • 通过z-index明确层级,确保文字始终在进度条上方
  • 保留mix-blend-mode: difference,白色文字在深色进度条上会显示为浅色,在浅色背景上显示为深色,完美匹配你想要的配色效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:25:17