我正在尝试调整iframe的大小以适合内容。看完其他人的做法后,我认为最简单的方法是获取iframe的scrollHeight并相应地调整iframe的大小。我在iframe标记中使用onload来运行它。在这个主题上,我编写了数十种变体,但没有成功。

 function resizeIFrame(){

     var sHeight, frame;

      frame = document.getElementById("bigFrame");
      sHeight = frame.scrollHeight;
      frame.style.height = sHeight + 'px';
    }


当我警告sHeight变量时,我得到的是框架的高度,而不是scrollHeight。这表明我可能没有正确收集scrollHeight。

我知道这个问题可能与以前的很多问题相似,但是有很多方法可以解决这个问题,并且可以提供更多的答案。我想知道这种调整iframe大小以适合内容的方法有什么问题?

这是html。

   <div id="contentContainer">
       <iframe id="bigFrame"
                src="home/home.html"
                name="mainFrame"
                onload="resizeIFrame()"
                onresize="resizeIFrame()"
                scrolling="no"
                seamless;  >
            </iframe>
   </div>

最佳答案

好吧,我让它完美运行。
    添加-contentWindow.document.body.scrollHeight-使我能够获取scrollHeight。我试图从变量获取scrollHeight。这没用。有效的方法是直接从文档中获取scrollHeight。

我必须在每页底部添加一些空间。因此+80;。不幸的是,每次调用该函数仅增加80。重新调整之前将帧高度重置为0px解决了该问题。

所以你去了。此函数通过获取scrollHeight并将iframe的高度设置为匹配大小,以调整iframe的大小以适合其内容。

 function resizeIFrame(){

        var sHeight, frame;

           frame = document.getElementById("bigFrame");
           frame.style.height = '0px';
           sHeight = document.getElementById('bigFrame').
                  contentWindow.document.body.scrollHeight + 80;
           frame.style.height = sHeight + 'px';
     }

07-24 09:44
查看更多