例如:
<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>
我希望它能够根据里面的内容来调整它的高度,而不使用滚动。
当前回答
我是用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';
};
其他回答
jq2('#stocks_iframe').load(function(){
var iframe_width = jq2('#stocks_iframe').contents().outerHeight() ;
jq2('#stocks_iframe').css('height',iframe_width); });
<iframe id='stocks_iframe' style='width:100%;height:0px;' frameborder='0'>
避免使用内联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';
});
以下是精简版:
<iframe src="hello.html" sandbox="allow-same-origin"
onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';">
</iframe>
<script type="text/javascript">
function resizeIframe(obj) {
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
这是不工作的chrome。但是在firefox上工作。
您可以使用这个库,它既能正确地调整iframe的初始大小,也能通过检测iframe内容的大小变化(通过setInterval中的常规检查或通过MutationObserver)并调整它来保持它在正确的大小。
https://github.com/davidjbradshaw/iframe-resizer
他们也是一个React版本。
https://github.com/davidjbradshaw/iframe-resizer-react
这适用于交叉和相同域的iframe。