vue項(xiàng)目使用iframe自適配高度

1.原生 JS 實(shí)現(xiàn)(同域場(chǎng)景),通過監(jiān)聽 iframe 加載事件,讀取其內(nèi)部文檔高度并動(dòng)態(tài)調(diào)整容器高度,無需額外依賴。

實(shí)現(xiàn)步驟:
模板定義:在組件中添加 iframe 并綁定 ref 和 load 事件
高度計(jì)算:通過 contentWindow.document 獲取 iframe 內(nèi)容高度
延遲執(zhí)行:使用 setTimeout 確保內(nèi)容加載完成后再計(jì)算高度

示例代碼:

<template>
  <div class="iframe-container">
    <iframe
      ref="iframe"
      :src="iframeSrc"
      frameborder="0"
      width="100%"
      scrolling="no"
      @load="handleIframeLoad"
    ></iframe>
  </div>
</template>

<script>
export default {
  data() {
    return {
      iframeSrc: 'http://baidu.com' // 同域頁面路徑
    };
  },
  methods: {
    handleIframeLoad() {
      // 延遲 1000ms 確保內(nèi)容完全加載
      setTimeout(() => {
        this.resetHeight();
      }, 1000);
    },
    resetHeight() {
      const iframe = this.$refs.iframe;
      if (!iframe) return;

      try {
        // 獲取 iframe 內(nèi)部文檔高度(兼容不同瀏覽器)
        const bodyHeight = iframe.contentWindow.document.body.scrollHeight;
        const htmlHeight = iframe.contentWindow.document.documentElement.scrollHeight;
        const maxHeight = Math.max(bodyHeight, htmlHeight);
        
        // 額外添加 150px 緩沖高度
        iframe.style.height = `${maxHeight + 150}px`;
      } catch (e) {
        // 跨域時(shí)會(huì)拋出異常,需使用方案二
        console.error('跨域訪問被阻止,請(qǐng)使用 iframe-resizer 插件');
      }
    }
  }
};
</script>

2.使用 iframe-resizer 插件(跨域/復(fù)雜場(chǎng)景)
iframe-resizer 是專門解決 iframe 自適應(yīng)問題的庫,支持跨域通信和動(dòng)態(tài)內(nèi)容變化監(jiān)聽,比原生方案更健壯。

實(shí)現(xiàn)步驟:
引入插件:主頁面和嵌入頁面分別引入對(duì)應(yīng)腳本
初始化配置:在主頁面調(diào)用 iFrameResize 方法
嵌入頁配置:引入內(nèi)容窗口腳本,無需額外代碼

示例代碼:
主頁面

<template>
  <div class="iframe-container">
    <iframe
      ref="iframe"
      src="http://baidu.com"
      frameborder="0"
      width="100%"
      scrolling="no"
    ></iframe>
  </div>
</template>

<script>
export default {
  mounted() {
    // 確保插件已加載(可在 public/index.html 中全局引入)
    if (window.iFrameResize) {
      // 初始化插件,配置跨域支持
      window.iFrameResize({
        log: false, // 生產(chǎn)環(huán)境關(guān)閉日志
        checkOrigin: false, // 允許跨域
        autoResize: true, // 內(nèi)容變化時(shí)自動(dòng)調(diào)整
        heightCalculationMethod: 'bodyOffset' // 高度計(jì)算方式
      }, this.$refs.iframe);
    }
  }
};
</script>

嵌入頁面,在被嵌入的 頁面中引入內(nèi)容窗口腳本:

<!-- 嵌入頁面頭部 -->
<script src="https://cdn.jsdelivr.net/npm/iframe-resizer@4.3.2/js/iframeResizer.contentWindow.min.js"></script>
<div class="dynamic-content">
  <!-- 動(dòng)態(tài)加載的內(nèi)容 -->
</div>

核心原理:主頁面通過 iframeResizer.min.js 監(jiān)聽消息,嵌入頁面通過 iframeResizer.contentWindow.min.js 主動(dòng)發(fā)送尺寸信息,實(shí)現(xiàn)跨域通信和實(shí)時(shí)調(diào)整。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容