【发布时间】:2011-11-11 04:18:11
【问题描述】:
我应该如何动态设置 iframe 的尺寸,以便尺寸灵活适应不同的视口尺寸?
例如:
<iframe src="html_intro.asp" width="100%" height="300">
<p>Hi SOF</p>
</iframe>
在这种情况下,高度会根据浏览器的窗口大小而有所不同。它应该根据浏览器窗口的大小动态设置。
在任何尺寸下,iframe 纵横比都应该相同。如何做到这一点?
【问题讨论】:
我应该如何动态设置 iframe 的尺寸,以便尺寸灵活适应不同的视口尺寸?
例如:
<iframe src="html_intro.asp" width="100%" height="300">
<p>Hi SOF</p>
</iframe>
在这种情况下,高度会根据浏览器的窗口大小而有所不同。它应该根据浏览器窗口的大小动态设置。
在任何尺寸下,iframe 纵横比都应该相同。如何做到这一点?
【问题讨论】:
如果你使用jquery,可以使用$(window).height();来完成
<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>
<script type="text/javascript" language="javascript">
$('.myIframe').css('height', $(window).height()+'px');
</script>
【讨论】:
不太清楚 300 应该是什么意思?错过错字?但是对于 iframe,最好使用 CSS :) - 我在导入 youtube 视频时发现它忽略了内联内容。
<style>
#myFrame { width:100%; height:100%; }
</style>
<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>
【讨论】:
height="300" 为 iframe 提供 300 像素的宽度。
您是否在 iframe 的定义中尝试过 height="100%" ?如果您在 CSS 中为“body”添加 height:100%,它似乎可以满足您的需求(如果不这样做,100% 将是“100% of your content”)。
编辑:不要这样做。 height 属性(以及 width 属性)必须有一个整数作为值,而不是字符串。
【讨论】:
height 属性的值必须是整数。我会编辑那个。 Graeme Leighfield 的解决方案是正确的。
我发现它在所有浏览器和设备(PC、表格和移动设备)上运行得最好。
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>
【讨论】:
最新的 css 规则将允许您直接使用视口,如下所示:
<iframe src="html_intro.asp" width="100vw" height="50vh">
<p>Hi SOF</p>
</iframe>
我个人喜欢通过操纵父容器来调整iframes:
<div class='iframe-parent'>
<iframe src="html_intro.asp">
<p>Hi SOF</p>
</iframe>
</div>
现在是 css:
.iframe-parent{
width: 100vw;
height: 50vh;
}
/* Expand to the entire container */
iframe{
width: 100%;
height: 100%;
}
【讨论】:
高度因浏览器的窗口大小而异。应该根据浏览器窗口的大小动态设置
<!DOCTYPE html>
<html>
<body>
<center><h2>Heading</h2></center>
<center><p>Paragraph</p></center>
<iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
</body>
</html>
【讨论】: