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

如何用JavaScript为YouTube的iframe嵌套两层自定义div容器?

给YouTube嵌入iframe添加双层嵌套响应式容器的解决方案

你只需要在原有代码基础上新增一层外层容器,调整嵌套层级即可实现需求,修改后的代码如下:

var embedItem = document.querySelectorAll('iframe[src*="youtube"]');
embedItem.forEach(function(eachEmbed){
  // 创建最外层容器
  let outerWrapper = document.createElement('div');
  outerWrapper.classList.add('video-wrapper', 'rounded');
  
  // 创建中间响应式容器
  let innerWrapper = document.createElement('div');
  innerWrapper.classList.add('embed-responsive', 'embed-responsive-16by9');
  
  // 按层级嵌套元素:iframe → 中间容器 → 外层容器
  innerWrapper.appendChild(eachEmbed.cloneNode(true));
  outerWrapper.appendChild(innerWrapper);
  
  // 替换原iframe节点
  eachEmbed.replaceWith(outerWrapper);
});

关键修改点:

  • 新增outerWrapper作为最外层容器,添加你需要的video-wrapper和rounded类
  • 保留原有的响应式容器逻辑,将其作为中间层嵌套进外层容器
  • 调整元素嵌套顺序,确保最终结构符合预期

执行这段代码后,会生成你需要的HTML结构:

<div class="video-wrapper rounded">
      <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/jTwdtMzZMds"
                     allowfullscreen="true" title="YouTube video"></iframe>
      </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:11:07