如何在不使用div的情况下让iframe响应?

时间:2017-02-27 19:12:03

标签: javascript html css wordpress iframe

我从这篇帖子(Making an iframe responsive)中了解到,通过在iframe周围添加一个带有类的容器来使iframe响应,例如,

<div class="intrinsic-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/I4YoBuJCbfo" frameborder="0" allowfullscreen></iframe>
</div>

是否可以直接在我的帖子中嵌入<iframe>...</iframe>(不使用<div>...</div>)?我尝试了这些解决方案,但所有这些解决方案都不起作用。

enter image description here

PS:我在WordPress中使用两列布局。视频比例可以是16:9(来自YouTube),4:3(来自腾讯)等。这是一个临时的demo

3 个答案:

答案 0 :(得分:6)

如果你可以使用在没有额外包装元素的情况下可行的视口单元。

整页宽度:

iframe {
  width: 100vw;
  height: 56.25vw; /*16:9*/
}
<iframe width="560" height="315" src="https://www.youtube.com/embed/I4YoBuJCbfo" frameborder="0" allowfullscreen></iframe>

半页宽度:

iframe {
  width: 50vw;
  height: 28.125vw; /*16:9*/
}
<iframe width="560" height="315" src="https://www.youtube.com/embed/I4YoBuJCbfo" frameborder="0" allowfullscreen></iframe>

答案 1 :(得分:1)

这里的关键是你想要保持的高度和宽度比。我冒昧地使用jQuery而不是javascript来做到这一点。单击按钮后会触发代码。它计算iframe的宽度和高度比,并根据您的需要进行调整(在这种情况下,我假设您希望它填充容器宽度)。

如果您在一个页面上有多个视频并在窗口大小调整和页面加载时运行代码,您可能希望遍历所有视频。

以下是JSFiddle

希望有所帮助:)

<强> HTML

<iframe id="iframe" width="640" height="360" src="https://www.youtube.com/embed/4SDVkdcO8ts" frameborder="0" allowfullscreen></iframe>
<button id="button" style="float: left">Click me!</button>

<强>的jQuery

$(document).ready(function(){
  $("button").click(function(){
    var ratio = $("#iframe").height() / $("#iframe").width();
    $("#iframe").width("100%");
    var newWidth = $("#iframe").width();
    $("#iframe").width(newWidth);
    $("#iframe").height(newWidth*ratio);
    $("button").text("resize the window and click me again!");
  });
});

答案 2 :(得分:0)

使用bootstrap类使iframe响应。

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" allowfullscreen
            src="//www.youtube.com/embed/zpOULjyy-n8?rel=0" >
    </iframe>
</div>