例如:
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
我希望它能够根据里面的内容来调整它的高度,而不使用滚动。
例如:
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
我希望它能够根据里面的内容来调整它的高度,而不使用滚动。
当前回答
我在过去调用iframe时遇到过问题。onload用于动态创建iframe,所以我用这种方法来设置iframe大小:
iFrame视图
var height = $("body").outerHeight();
parent.SetIFrameHeight(height);
主要的观点
SetIFrameHeight = function(height) {
$("#iFrameWrapper").height(height);
}
(这只会工作,如果两个视图在同一个域)
其他回答
避免使用内联JavaScript;你可以使用一个类:
<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>
用jQuery引用它:
$('.iframe-full-height').on('load', function(){
this.style.height=this.contentDocument.body.scrollHeight +'px';
});
jQuery的.contents()方法允许我们在DOM树中搜索元素的直接子元素。
jQuery:
$('iframe').height( $('iframe').contents().outerHeight() );
记住,在iframe内的页面主体必须有它的高度
CSS:
body {
height: auto;
overflow: auto
}
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)”
我是用AngularJS做的。Angular没有ng-load,但是创建了一个第三方模块;安装下面的凉亭,或在这里找到它:https://github.com/andrefarzat/ng-load
获取ngLoad指令:bower install ng-load——save
设置你的iframe:
<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>
控制器resizeIframe功能:
$scope.resizeIframe = function (event) {
console.log("iframe loaded!");
var iframe = event.target;
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};
这适用于我(也与多个iframe在一个页面):
$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});