设置iframe高度后加载内容

时间:2018-11-06 20:42:10

标签: javascript

尝试调整框架高度以适合加载内容。

HTML

<iframe src="forum/viewforum.php?f=6" width="100%" frameborder="0" 
scrolling="no" onload="resizeIframe(this)"></iframe>

JS

  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }

如何在所有内容加载完毕之前停止运行该功能。我尝试过:

document.addEventListener('DOMContentLoaded', function() {

  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }

}, false);

$(document).ready(function(){

  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }

});

但不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

(function () {

    function setSize() {
      var frame = document.getElementById("iframe");
      frame.style.height = frame.contentWindow.document.body.offsetHeight + 'px';
    }
    
    window.addEventListener('load', setSize, false )


}) ();
    <iframe src="content.html" id="iframe" scrolling="no" frameborder="0"></iframe>