如何在不刷新页面的情况下调整iframe的大小?

时间:2015-06-23 08:56:58

标签: javascript jquery html iframe

我在iframe中嵌入了一些swf,但只有刷新页面时才调整iframe的大小,然后如果我选择其他的,那么将显示为所有swf,不仅动画也是背景。这就是我正在使用的

if ( 'resizeIframe' === $('#onPlayAction').val() ) {
    var ifrEl = $('div.player-container iframe.page-iframe')[0];

    $(ifrEl).show();
    ifrEl.src = htmlPageBrowserUri;
    ifrEl.onload = function() {
      ifrEl.width = ifrEl.contentWindow.document.body.scrollWidth;
      ifrEl.height = ifrEl.contentWindow.document.body.scrollHeight;
    }
  } 

2 个答案:

答案 0 :(得分:1)

有三种方法可以做到这一点。

  1. 您可以在每个窗口调整大小时更改大小
  2. $(window).on('resize', function (){
    
      ifrEl.width = ... ;
      ifrEl.height = ... ;
    
    })
    
    1. 您可以使用一些jQuery插件,例如iFrame Resizer

    2. 你可以使用一些漂亮的CSS技巧。去搜索responsive iframes using css,你会发现很多好的答案。

    3. 我希望这一切对你有帮助。

答案 1 :(得分:0)

我怀疑你的代码问题可能是两行:

   ifrEl.src = htmlPageBrowserUri;
    ifrEl.onload = function() {

问题是第一行设置了帧地址,但是第二行设置了onload事件,可能是在页面加载之前?因此,当页面加载时,行设置onload事件已经运行&所以doens没有设置。

我不太明白你问题中的文字(对不起!)但是下面的代码成功调整了iframe的大小 - 它运行了#on;'在框架的页面中:

<body onload="setParent()">

如果它是相关的,iframe本身就有属性:

 <iframe id="neckfinishframe"  style="width:100%;overflow-x:hidden" src=".. etc">

就我而言,我只关心身高。宽度为100%。

在iFrame页面中,此代码从onload事件运行,以将iframe高度修改为页面的高度,加上一点。这是为了避免在iframe中显示一组滚动条。

function setParent() {
// runs onload in iframe page
// in my case I have to run it from the frame page because I need to know the page rendered height in order to set the iframe height

var f;
try {f = parent.getElementById("neckfinishframe")} catch (e) {};
if (f != null) f.style.height=(this.document.body.scrollHeight+30)+"px";

}

注意 - 我没有尝试过这种跨浏览器,但我知道它适用于IE浏览器。

相关问题