首页 文章

阻止iframe阻止父文件的滚动?

提问于
浏览
13

我似乎与iframes和滚动的其他人有相反的问题 . 我需要iframe(包含youtube视频)以防止滚动主文档 . 如果我将鼠标悬停在它上面,页面将不会使用滚轮滚动,并且根据触摸设备的最新镀铬金丝雀模拟,我无法将手指放在框架上并滚动主文档 . 有办法阻止这个吗?我的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%;
 }

4 回答

  • 3

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

    如果您不需要与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>
    
  • 1

    我有横向滚动禁用,如下所示:

    html, body {
        overflow-x: hidden
    }
    

    在一个带有 iframe 的页面上,如果我试图通过触摸并在Safari for iPad或iPhone上移动iframe来垂直滚动页面,我就不能 .

    这为我修好了:

    * {
        -webkit-overflow-scrolling: touch
    }
    
  • 9

    曾经有一个scrolling attribute,但它在html5中已弃用 . 试试这个:

    iframe {
        overflow: hidden;
    }
    

    不要忘记在某处设置你的宽度和高度!

    如果你想尝试iframe滚动属性,你可能会喜欢这样:

    <iframe src="blah.html" width="200" height="200" scrolling="no"></iframe>
    

    请参见此处的工作示例:http://jsfiddle.net/4dt4zhwt/1/

  • 1

    我不知道你是否找到了解决这个问题的办法,但我遇到了同样的问题,我网站上的所有iframe(twitter,facebook和youtube)都阻止了网页本身的滚动 . 经过大量的调试和咖啡后,我发现它,至少在我的情况下,它被隐藏在一个 overflow-x: hidden 隐藏我已经设置了一个表单元素4/5父母了 . 删除溢出属性为我解决了问题,希望它适合你!

相关问题