如何删除底部多余的 iframe space?

How can I remove the extra iframe space at the bottom?

这是我关于 Whosebug 的第一个问题。我想要做的是使用 javascript 在测试 div 中创建一个 iframe,并在其中添加 html 代码。我也想动态调整 iframe 的高度。只有当我将 dynamic_div 的高度设置为超过 150px 时,下面的代码才对我有用。如果 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>

因为你的<div id="container">

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

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

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