javascript 如何使 iframe 响应全高和全宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31070963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:12:59  来源:igfitidea点击:

How to make an iframe responsive full height and full width

javascripthtmlcssiframe

提问by Stranger B.

I'm embedding a youtube/dailymotion videos and I want to make the iframe responsive and especially full height , the same height as the window :

我正在嵌入一个 youtube/dailymotion 视频,我想让 iframe 响应,尤其是全高,与窗口的高度相同:

I made a responsive Iframe but not full height !

我做了一个响应式 Iframe 但不是全高!

Here is my code

这是我的代码

   <div  class="video-container">
                       <iframe height="100%" width="100%"  src="https://www.youtube.com/embed/7ipiybRLqZc" frameborder="0" allowfullscreen></iframe> 
                </div>

CSS :

CSS :

.video-container {
    position: relative;
    padding-bottom: 100%;
    height:100%;

}

.video-container iframe, .video-container object, .video-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    margin:0px;
}

DEMO + CODE JS FIDDLE

演示 + 代码 JS 小提琴

回答by SW4

Use viewport percentage lengths, vwand vhto set the height and width of the iframe. Optionally, use calcto subtract 4pxas the player seems to add this.

使用视口百分比长度vwvh设置 的高度和宽度iframe。或者,使用calc来减去,4px因为玩家似乎添加了它。

Viewport-percentage lengths defined a length relatively to the size of viewport, that is the visible portion of the document. Only Gecko-based browsers are updating the viewport values dynamically, when the size of the viewport is modified (by modifying the size of the window on a desktop computer or by turning the device on a phone or a tablet).

视口百分比长度定义了相对于视口大小的长度,即文档的可见部分。只有基于 Gecko 的浏览器会在修改视口大小时动态更新视口值(通过修改台式计算机上的窗口大小或通过手机或平板电脑上的设备)。

body {
  margin: 0;
}
iframe {
  height:calc(100vh - 4px);
  width:calc(100vw - 4px);
  box-sizing: border-box;
}
<iframe src="https://www.youtube.com/embed/7ipiybRLqZc" frameborder="0" allowfullscreen></iframe>

回答by 4dgaurav

Demo

演示

HTML

HTML

<div class="video-container">
    <div class="h_iframe">
        <!-- a transparent image is preferable -->
        <img class="ratio" src="http://placehold.it/16x9" />
        <iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

CSS

CSS

html, body {
    height:100%;
margin:0;
}

.h_iframe {
    position:relative;
}
.h_iframe .ratio {
    display:block;
    width:100%;
    height:auto;
}
.h_iframe iframe {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}