首页 > 解决方案 > 我可以阻止 Youtube 嵌入 iframe 在与之交互时滚动到视图中吗?它打破了我的手风琴

问题描述

我有这个手风琴,它基本上由一个带有 set的外部heightdiv和overflow-y: hidden一个带有从 CMS 提供的动态内容的内部div 组成(以及一个从外部 div 中删除高度和溢出规则的按钮,非常简化)。

有时内部 div 中的内容包含嵌入的 Youtube 视频 (iframe)。每当 Youtube 视频被外部 div 的“切断”overflow-y: hidden时,就会出现问题。当您开始与视频交互时,通过单击播放、停止等为其赋予焦点时,视频会滚动到视图中,并且放置在视频上方的任何内容都可能会在外部 div 的上边缘上方消失,从而变得不可见。无法将其滚动回视图,因为外部 divoverflow-y: hidden会像预期的那样禁用滚动 - 但显然不是在将焦点放在视频上时。

有没有办法在给视频焦点时防止 div 滚动?显然overflow-y: hidden是不够的。我在 Chrome 中遇到过这个问题。在 Firefox 中,默认情况下它似乎工作正常 - 摆弄视频时不会发生滚动。

如果可能的话,我正在寻找一个只有 CSS 的解决方案,最好没有 JS。

我创建了一个 codepen 来说明问题,您可以在其中看到它:https ://codepen.io/monodrive/pen/poEraWK

非常简化的代码看起来像这样(手风琴功能完全被忽略了,因为它与重现此行为无关)。

HTML:

<div class="outer">
  <div class="inner">
    Hello there. This text comes from the inner div. It will scroll out of the viewport once you start interacting with the Youtube video below, and cannot be scrolled into view again. Can the initial scroll be prevented? (seems to happen in Chrome only)<br>
    <iframe width="560" height="315" src="https://www.youtube.com/embed/DWcJFNfaw9c" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  </div>
</div>

CSS:

.outer {
  max-height: 250px;
  overflow-y: hidden;
  border: 1px solid green;
}

标签: htmlcss

解决方案


推荐阅读