html - 阻止 Iframe 阻止父文档的滚动?

标签 html css iframe

对于 iframe 和滚动,我似乎遇到了与其他所有人相反的问题。我需要 iframe(包含一个 youtube 视频)来不阻止主文档的滚动。如果我将鼠标悬停在它上面,页面将不会随着滚轮滚动,并且根据触摸设备的最新 chrome canary 模拟,我也无法将手指放在框架上并滚动主文档。有什么办法可以阻止吗?我的 CSS 如下:

.GalleryVideoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
width:95%;
margin:auto;
display:block;
 }

.GalleryVideoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
 }

最佳答案

这个问题不清楚,所以我在下面详细介绍了实现这种效果的各种方法及其工作原理。

如果您不需要与 iframe 交互,快速而肮脏的解决方案是使用 pointer-events: none; .这会将 iframe 放在页面上,并且不允许它滚动。但是,它也不允许您单击它。这显然不适用于 YouTube 视频,但重要的是要知道这是一个选项。

如果您需要与 iframe 交互,无论是播放视频还是单击链接,您只需确保 iframe 足够大以显示完整内容。我不确定 OP 遇到了什么具体问题,因为我们没有他们的 HTML,但是如果您滚动并且 iframe 也没有尝试滚动,它不会阻止父级滚动。

基本上,如果您将光标放在 iframe 上并滚动,则 iframe 将首先接收事件。如果不需要滚动(不能滚动或已经到达 iframe 的底部),事件将传播到父级。

最后,如果您有一个需要滚动的 iframe,但您希望在光标位于 iframe 上时滚动父级,那么您就不走运了。没有办法通知 iframe 有时用户想要滚动整个页面。这就是 iframe 的工作原理。您可以将光标从 iframe 中移开以滚动,或者滚动到 iframe 的底部并继续向下滚动页面。

使用问题中的 YouTube 视频和 CSS,我提供了一个演示供您查看。我还包含了两个相同的可滚动的 iframe,并将 pointer-events: none; 应用到其中一个以演示其工作原理。

.tall {
  height: 1500px;
}

.GalleryVideoWrapper {
  position: relative;
  padding-bottom: 56.25%;
  /* 16:9 */
  padding-top: 25px;
  height: 0;
  width: 95%;
  margin: auto;
  display: block;
}

.GalleryVideoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.scrolling-iframe {
  margin-top: 35px;
  display: inline-block;
  height: 500px;
}

.no-scroll {
  pointer-events: none;
}
<div class="tall">
  <div class="GalleryVideoWrapper">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/hzB53YL78rE?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
  </div>
  <iframe class="scrolling-iframe" src="https://www.wikipedia.org/" frameborder="1"></iframe>
  <iframe class="scrolling-iframe no-scroll" src="https://www.wikipedia.org/" frameborder="1"></iframe>
</div>

关于html - 阻止 Iframe 阻止父文档的滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27084876/

相关文章:

html - 如何实现 ngx-datatable 列标题的工具提示

html - 我在网站的阿拉伯语版本左侧有一个巨大的空白

javascript - 使 css 数字看起来漂亮

html - 内联样式和内部样式的优先级

html - 是否可以将第二个 child 的宽度设置为行列表中最大的一个?

php - 我可以在同一页面上使用多个内容类型吗?

javascript - Vue如何正确遍历列表?

javascript - 拒绝在框架中显示网站,因为它的 'X-Frame-Options'

javascript - 允许用户上传 HTML/JS 文件的风险

html - CSS 更改后 iPad iframe 滚动到顶部