设置相对于宽度的高度

时间:2013-12-02 23:20:41

标签: javascript iframe responsive-design

如何根据宽度设置iframe的高度?

<iframe width="100%" height="auto" id="youtube" ... >

window.onresize function() {
    document.getElementById("youtube").style.height = this.style.width*0.63;
}

我只想使用javascript。

4 个答案:

答案 0 :(得分:1)

您可以创建在后台运行的间隔,并更新要匹配的帧。

function autoAdjustWidth(){
    var frm=document.getElementById('myFrame');
    console.log(frm.offsetWidth);
    frm.height=frm.offsetWidth;
}
autoAdjustWidth();
window.setInterval(autoAdjustWidth,300);

请参阅jsfiddle

答案 1 :(得分:1)

看起来你没有使用window.onresize,错过了等号以声明函数...

<iframe width="100%" height="auto" id="youtube" ... >
window.onresize = function(event) {
    document.getElementById("youtube").style.height = document.getElementById("youtube").style.width*0.63;
}

答案 2 :(得分:1)

通过一些更改,您的示例几乎正确:

 // using =
 window.onresize = function() {
    var iFrame =  document.getElementById("youtube");
    // use iFrame width instead of "this" which is the windows width
    iFrame.style.height = iFrame.style.width;
 }

答案 3 :(得分:0)

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

Complete gist here. Live example here.