适合其内容的Iframe高度

abc*_*123 5 javascript iframe jquery

有没有办法让iframe的高度适合它的内容?你能告诉我怎么做吗?我试着在网上搜索并试用代码,但没有运气

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta NAME="Description" content="Communigate Technologies" />
<meta HTTP-EQUIV="Cache-Control" content="no-cache" />
<meta HTTP-EQUIV="pragma" content="no-cache" />

<title></title>

</head>

<body>
    <div align="center" style="z-index:1;">
    <?php include 'header.html' ?>

        <iframe align=top width=800px src="aboutus1.php" frameborder=1 border=0 framespacing=0 SCROLLING=no id="bodyframeid" name="bodyframename"></iframe>

    </div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

Chr*_*des 6

由于我们处于CSS3时代,您可以使用视口单元来完成此操作.这些单位允许您根据视口宽度和视口高度的百分比指定大小.这是用户的视口,也称为屏幕.但是,在我尝试过的所有主流浏览器中,如果你把一个iframe放在一个div中,这个div位于另一个div内并且相对定位,则视口单元相对于这个div.由于100个视口高度单位意味着100%高度,您可以这样做:

<div id="parent">
    <div id="wrapper" style="position:relative">
        <iframe style="position:absolute;top:0px;width:100%;height:100vh;" src="http://anydomain.com"></iframe>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我发现这是最好的解决方案,因为它是跨域的,并且显示完全像你想要它没有任何javascript或其他复杂的东西.

最重要的是,它适用于所有浏览器,甚至是移动浏览器(在Android和iphone上测试)!


Web*_*vie 0

如果您的文档和 iframe 内容具有相同的来源(在您的示例中,您具有相同的来源),您可以从主文档运行:

var iframe = document.getElementById('my-iframe')
var content = iframe.contentWindow.document.getElementById('content')
var height = content.offsetHeight + 15 //add something to support paddings etc.
iframe.style.height = height + 'px'
var width = content.offsetWidth + 15
iframe.style.width = width + 'px'
Run Code Online (Sandbox Code Playgroud)

但请检查您适应的“内容”元素的大小,因为该元素通常比可见内容大得多。