【问题标题】:Poster frame of embedded YouTube video larger than video嵌入 YouTube 视频的海报帧大于视频
【发布时间】:2019-07-24 21:38:54
【问题描述】:

我正在将 YouTube 视频嵌入 HTML 页面。我希望视频在浏览器窗口中尽可能大。这是我用于嵌入式 iframe 的 CSS:

iframe {
  position: absolute;
  left:0;
  top:0;
  height:100%;
  width:100%;
  overflow: hidden;
}

当视频播放时,它很好地适合窗口,保持其纵横比并显示上下或左右的空白空间,正如我所期望的那样。

但是,初始海报图像完全填满了窗口。我希望它调整其高度和宽度,使其具有与视频相同的尺寸和位置。

我认为我可以访问视频 iframe 中的元素,以发现视频的尺寸。但是,当我使用document.querySelector("iframe").contentWindow.document 时,我收到一条错误警告,指出访问跨域框架被阻止。

如何检测视频的纵横比,以便正确设置 iframe 的尺寸?

【问题讨论】:

    标签: javascript css iframe


    【解决方案1】:

    我找到了解决办法。但是,这意味着为视频的尺寸提供硬编码值。

    在 YouTube 上,我右键单击以调出“Nerds 统计信息”并注意 Current / Optimal Res(例如:1280x720@30)。在 HTML 中,我以--width--height CSS 变量的形式提供相关信息:

    HTML:

    <iframe style="
              --width:1280;
              --height:720;
            "
            src="https://www.youtube.com/embed/fUyU3lKzoio"
            frameborder="0"
            allowfullscreen>
    </iframe>
    

    在 CSS 中,我将 widthheight 设置为窗口的完整大小(使用 vwvh 单位,它们返回智能手机和平板电脑上的完整可用大小)。我还限制了max-heightmax-width,以确保尊重视频的纵横比:

    CSS:

    iframe {
      width:  100vw;
      height: 100vh;
      max-height: calc(100vw / var(--width) * var(--height));
      max-width:  calc(100vh * var(--width) / var(--height));
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 2017-07-25
      • 2017-10-22
      • 2021-12-04
      • 2012-06-25
      • 1970-01-01
      • 2016-11-26
      • 2019-01-31
      相关资源
      最近更新 更多