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

如何仅用JavaScript为HTML5视频添加叠加文本或上下字幕

解决方案

一、让字幕显示在视频正上方/正下方

你之前的代码文本显示在右侧,是因为<video>默认是行内块元素,相邻文本会和它在同一行排列。解决思路是给每个视频套一个块级容器,让字幕自动换行到上下位置:

// 定义视频对应的字幕文本
const videoCaptions = {
  "vid-1": "Video 1 - Greenery",
  "vid-2": "Video 2 - Island"
};

// 遍历所有视频元素
document.querySelectorAll("#vids video").forEach(video => {
  // 创建块级容器
  const wrapper = document.createElement("div");
  // 把容器插在视频前面
  video.before(wrapper);
  // 将视频移入容器
  wrapper.appendChild(video);
  
  // 创建字幕元素
  const caption = document.createElement("div");
  caption.textContent = videoCaptions[video.id];
  // 可选:让字幕居中对齐
  caption.style.textAlign = "center";
  
  // 要放视频上方就用 wrapper.insertBefore(caption, video)
  // 下面的写法是放在视频正下方
  wrapper.appendChild(caption);
});

处理后每个视频和字幕都会被块级容器包裹,字幕自然会显示在视频正下方,调整插入位置就能放到正上方。

二、实现叠加字幕(悬浮在视频上)

如果要让字幕直接叠加在视频上,用CSS定位就能实现,无需修改原HTML:

const videoCaptions = {
  "vid-1": "Video 1 - Greenery",
  "vid-2": "Video 2 - Island"
};

document.querySelectorAll("#vids video").forEach(video => {
  // 创建容器并设置相对定位(作为绝对定位的参考)
  const wrapper = document.createElement("div");
  wrapper.style.position = "relative";
  wrapper.style.display = "inline-block";
  
  video.before(wrapper);
  wrapper.appendChild(video);
  
  // 创建字幕元素并设置绝对定位
  const caption = document.createElement("div");
  caption.textContent = videoCaptions[video.id];
  // 定位到视频底部居中,可自行调整top/left改变位置
  caption.style.position = "absolute";
  caption.style.bottom = "10px";
  caption.style.left = "50%";
  caption.style.transform = "translateX(-50%)";
  // 增强可读性:白色文字+黑色阴影
  caption.style.color = "white";
  caption.style.textShadow = "0 0 3px black";
  caption.style.padding = "4px 8px";
  
  wrapper.appendChild(caption);
});

这段代码会让字幕悬浮在视频底部居中的位置,修改bottom为top就能把字幕移到视频顶部。

额外优化提示

如果样式较多,建议动态添加样式表来统一管理,避免重复写内联样式:

// 动态添加全局样式
const style = document.createElement("style");
style.textContent = `
  .video-wrapper {
    position: relative;
    display: inline-block;
    margin: 8px;
  }
  .video-overlay-caption {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    color: white;
    text-shadow: 0 0 3px #000;
    font-size: 14px;
    padding: 4px 8px;
  }
  .video-below-caption {
    text-align: center;
    margin: 4px 0;
    font-size: 14px;
  }
`;
document.head.appendChild(style);

之后创建字幕时直接添加类名即可:caption.classList.add("video-overlay-caption")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06