【问题标题】:How can I remove the extra iframe space at the bottom?如何删除底部多余的 iframe 空间?
【发布时间】:2015-02-04 21:07:25
【问题描述】:

这是我关于 stackoverflow 的第一个问题。我想要做的是使用 javascript 在测试 div 中创建一个 iframe 并在其中添加 html 代码。我也想动态调整 iframe 的高度。仅当我将 dynamic_div 的高度设置为超过 150 像素时,下面的代码才对我有用。如果 dynamic_div 的高度小于 150,它会自动将 iframe 的高度设置为 150。我该如何解决这个问题?

P.S : html 变量中的 html 代码是动态的。所以我无法更改其中的任何内容。

非常感谢。

<html>
<head>
</head>
<body>
<div id="test" style="border: 1px solid;"></div>
<script text="text/javascript">
var html = "<html><head></head><body><div id=\"container\" style=\"text-align:center;padding:8px 0;background-color:#f0f0f0;border:1px dashed;\"> <div id=\"dynamic_div\" style=\"width:100%;height:50px\">Some Content</div></body></html>";

function ui_aa(element_id,content){ // create an iframe and add txt into it.
    var iframe = document.getElementById(element_id).appendChild(document.createElement('iframe')),
    doc = iframe.contentWindow.document;
    iframe.style.cssText = "width:100%";
    iframe.frameBorder = 0;
    iframe.scrolling= 'no';
    doc.open().write(content);
    doc.close(); 
    doc.body.style.cssText = "margin:0px;padding:0px;height:100%";
    var height = doc.body.scrollHeight;
    iframe.height = height;
};
ui_aa('test',html);
</script>
</body>
</html>

【问题讨论】:

    标签: javascript html css iframe


    【解决方案1】:

    iframe 以未知原因获取高度值,给它一个高度值,例如 0 成功了,doc.body.style.cssText 将高度值覆盖为 100% 无论如何,所以你不需要担心。

    function ui_aa(element_id,content){ // create an iframe and add txt into it.
        iframe.height= '0';
    };
    

    例如JSFiddle

    【讨论】:

      【解决方案2】:

      因为你的&lt;div id="container"&gt;

      自动它不会像您的 iframe 一样高。 为其添加一些样式。

      #container {
          height: 100%;
          display: block;
      }
      

      【讨论】:

      • 感谢您对 Tamas 的评论,但它不起作用。