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

如何创建可自适应缩放、逐字显示的灰色透明字幕框?

字幕框问题修复方案

1. 先清理冗余CSS

直接删掉原来代码里所有和textarea相关的样式(比如输入框的resize、border、padding这些),这些完全是多余的,留着只会干扰样式。

2. 写自适应灰色透明字幕框样式

用下面的CSS替换原来的容器样式,完美解决自适应和透明需求:

.subtitle-box {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(60, 60, 60, 0.7); /* 灰色半透明,最后一个数值调透明度 */
  color: #fff;
  padding: 10px 18px;
  border-radius: 6px;
  display: inline-block; /* 核心:让盒子跟着内容自动变宽 */
  max-width: 85%; /* 防止内容太长撑满屏幕,可按需调整 */
  text-align: center;
  opacity: 0;
  transition: opacity 0.4s ease; /* 淡入淡出动画 */
}

.subtitle-box.show {
  opacity: 1;
}
  • display: inline-block是自适应大小的关键,盒子宽度会完全贴合内容长度
  • rgba背景直接实现灰色透明效果,不用额外加滤镜

3. 配合你的JS模板调整逻辑

假设你原来的JS已经有逐字打印的基础,只需要把操作对象换成上面的.subtitle-box就行,这里给个适配的完整逻辑示例:

// 替换成你要展示的对话内容
const dialogList = [
  "今天天气不错啊",
  "是啊,适合出去走走",
  "那下午一起去公园吧?"
];

const subtitleEl = document.querySelector('.subtitle-box');
let currentIndex = 0;

// 逐字打印函数
function printText(text, nextStep) {
  let charIndex = 0;
  subtitleEl.textContent = '';
  subtitleEl.classList.add('show'); // 显示字幕框
  const timer = setInterval(() => {
    if (charIndex < text.length) {
      subtitleEl.textContent += text[charIndex];
      charIndex++;
    } else {
      clearInterval(timer);
      // 显示完停留2秒,然后隐藏切换下一段
      setTimeout(() => {
        subtitleEl.classList.remove('show');
        setTimeout(nextStep, 400); // 等淡出动画结束再执行下一步
      }, 2000);
    }
  }, 60); // 逐字速度,数值越小越快
}

// 启动字幕轮播
function startPlay() {
  if (currentIndex < dialogList.length) {
    printText(dialogList[currentIndex], () => {
      currentIndex++;
      startPlay();
    });
  }
}

// 页面加载后自动启动
window.onload = startPlay;

4. 简化HTML结构

不需要textarea,只需要一个空容器就行:

<div class="subtitle-box"></div>

这样改完,字幕框会自动跟着对话内容调整宽度,灰色透明效果也到位,逐字显示+自动切换的逻辑也能正常跑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:43:15