iframe高度自适应里面html内容的高度

2023-12-13 05:53:36

在Angular中,要确保iframe的高度一定大于加载的外部HTML内容的高度,你可以使用Angular的HostListener和Renderer2来实现动态设置iframe的高度。

首先,在组件类中引入Renderer2和ViewChild:

 

typescript

import { Component, Renderer2, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

然后在组件类中使用ViewChild来获取iframe元素,并使用Renderer2来动态设置iframe的高度:

typescript

export class YourComponent implements AfterViewInit {
  @ViewChild('iframe') iframe: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    this.adjustIframeHeight();
  }

  @HostListener('window:resize', ['$event'])
  onResize(event: Event) {
    this.adjustIframeHeight();
  }

  adjustIframeHeight() {
    const iframeElement = this.iframe.nativeElement;
    if (iframeElement) {
      const contentHeight = iframeElement.contentWindow.document.body.scrollHeight;
      this.renderer.setStyle(iframeElement, 'height', contentHeight + 'px');
    }
  }
}

在模板文件中,使用ViewChild给iframe添加一个标识符,并绑定src属性:

html

<iframe #iframe [src]="'your_external_html_url'"></iframe>

上述代码中,adjustIframeHeight函数会在组件初始化后和窗口resize事件时被调用,它会获取iframe内部内容的高度,并将iframe的高度设置为内容高度,从而保证iframe的高度一定大于加载的外部HTML内容的高度。

文章来源:https://blog.csdn.net/zwjapple/article/details/134953516
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。