比如说。
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
我希望它能够根据里面的内容来调整高度,而不使用滚动。
将此添加到你的<head>
部分。
<script>
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
并将你的iframe改为这样。
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
正如在sitepoint讨论上发现的那样。
hjpotter92的建议在Safari中不起作用! 我对脚本做了一个小的调整,所以现在它在Safari中也能工作。
唯一的变化是在每次加载时将高度重置为0,以便使一些浏览器能够降低高度。
把这个添加到<head>
标签。
<script type="text/javascript">
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
并在你的iframe中添加以下onload
属性,像这样
<iframe onload='resizeIframe(this)'></iframe>
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
}
document.getElementById(id).height=(newheight) + "px";
document.getElementById(id).width=(newwidth) + "px";
}
将此添加到你的iframe中。 onload="autoResize('youriframeid')"