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

如何用JS实现网站加载随机播放视频且每个视频对应独立描述与跳转链接

调整后的完整实现代码

HTML部分(替换你原来的video标签代码即可)

<figure class="wp-block-video">
  <a rel="noreferrer noopener" target="_blank" id="videoWrapLink">
    <video autoplay muted loop playsinline style="max-width:100%" id="OracleVid"></video>
  </a>
  <figcaption>
    <strong>
      <code>
        <span style="color:#111111" class="has-inline-color" id="videoDesc"></span>
      </code>
    </strong>
    <a rel="noreferrer noopener" target="_blank" id="videoBottomLink"></a>
  </figcaption>
</figure>

JS部分(替换你原来的script标签内的代码)

// 每个视频对应配置:视频地址、跳转链接、描述文本、底部链接显示文本,新增视频直接往数组加对象即可
const videoConfigList = [
  {
    src: "http://localhost/website/wp-content/uploads/2021/10/logitech1_xlarge_preview.mp4",
    jumpLink: "https://website1.com",
    description: "罗技产品宣传视频",
    linkShowText: "website1.com"
  },
  {
    src: "http://localhost/website/wp-content/uploads/2021/10/6b_xlarge_preview.mp4",
    jumpLink: "https://website2.com",
    description: "6B系列产品演示",
    linkShowText: "website2.com"
  },
  {
    src: "http://localhost/website/wp-content/uploads/2021/10/elementor1_xlarge_preview.mp4",
    jumpLink: "https://website3.com",
    description: "Elementor模板效果展示",
    linkShowText: "website3.com"
  }
];

window.onload = function () {
  // 随机选中一个视频配置
  const randomItem = videoConfigList[Math.floor(Math.random() * videoConfigList.length)];
  // 获取页面DOM元素
  const videoEl = document.getElementById("OracleVid");
  const wrapLinkEl = document.getElementById("videoWrapLink");
  const descEl = document.getElementById("videoDesc");
  const bottomLinkEl = document.getElementById("videoBottomLink");
  // 批量赋值对应属性
  videoEl.src = randomItem.src;
  wrapLinkEl.href = randomItem.jumpLink;
  descEl.innerText = randomItem.description;
  bottomLinkEl.href = randomItem.jumpLink;
  bottomLinkEl.innerText = randomItem.linkShowText;
  // 加载视频
  videoEl.load();
};

核心改动说明

  • 将原来仅存储视频地址的数组改为对象数组,每个视频对应绑定独立的跳转链接、描述文本等信息,后续新增视频只需要在数组内添加对应配置即可,维护成本低
  • 移除了原来的<source>子标签,直接给<video>标签赋值src,完全匹配你需要的DOM结构
  • 静态HTML提前写好固定的属性(比如rel="noreferrer noopener"、target="_blank"等),不需要JS动态生成,性能更好,逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:48:00