我想根据内容大小调整iframe的高度
这是我的组件文件:
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
constructor( private sanitizer: DomSanitizer){}
hideFeed(myFeed){
this.iframeURL = this.sanitizer.bypassSecurityTrustResourceUrl( myFeed.contentUrl);
this.showIframe = true;
这是我的HTML文件:
<div class="container-fluid" *ngIf = "showIframe" >
<div class="col-lg-12 col-md-12 col-xs-12" class="feedIframe">
<iframe scrolling="auto" frameborder="0"
style=" position: relative; height: 100%; width: 100%;" [src]="iframeURL">
</iframe>
<a (click) = "refreshPage()" class="button">
<span style="color: #555;" >BACK</span>
</a>
</div>
</div>
答案 0 :(得分:1)
这就是我最终的结果。 从我在网上找到的指令开始并使其正常工作。 有时加载页面需要一段时间,因此setTimeout。
import {Directive, ElementRef, OnInit, Renderer} from "@angular/core";
@Directive({
selector: "[iframeAutoHeight]"
})
export class IframeAutoHeightDirective implements OnInit {
private el: any;
private renderer: Renderer;
private prevHeight: number;
private sameCount: number;
constructor(_elementRef: ElementRef, _renderer: Renderer) {
this.el = _elementRef.nativeElement;
this.renderer = _renderer;
}
ngOnInit() {
const self = this;
if (this.el.tagName === "IFRAME") {
this.renderer.listen(this.el, "load", () => {
self.prevHeight = 0;
self.sameCount = 0;
setTimeout(() => {
self.setHeight();
}, 50);
});
}
}
setHeight() {
const self = this;
if (this.el.contentWindow.document.body.scrollHeight !== this.prevHeight) {
this.sameCount = 0;
this.prevHeight = this.el.contentWindow.document.body.scrollHeight;
this.renderer.setElementStyle(
self.el,
"height",
this.el.contentWindow.document.body.scrollHeight + "px"
);
setTimeout(() => {
self.setHeight();
}, 50);
} else {
this.sameCount++;
if (this.sameCount < 2) {
setTimeout(() => {
self.setHeight();
}, 50);
}
}
}
}
用法:
<iframe [src]="iframeUrl" iframeAutoHeight></iframe>
答案 1 :(得分:0)
首先,宣布在模板中处理onload
事件的函数load
:
<iframe scrolling="auto" frameborder="0" (load)="onload($event)"
style=" position: relative; height: 100%; width: 100%;" [src]="iframeURL">
</iframe>
其次,只要HTMLFrameElement
事件发生,就在组件中获取load
对象:
el: HTMLFrameElement;
onload(ev: Event) {
this.el = <HTMLFrameElement>ev.srcElement;
}
最后,您可以在组件中调整iframe大小,如下所示:
adjust() {
this.el.height="300";
this.el.width="300";
}
答案 2 :(得分:0)
将此添加到您的<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 discussion上找到。
*请注意,在以下问题上找到了此答案:Make iframe automatically adjust height according to the contents without using scrollbar? 对此https://stackoverflow.com/users/1190388/hjpotter92表示敬意。想要在此处添加它,因为纯Javascript答案适用于我的角度站点。