黑白梦黑白梦

  • 文章
  • 专栏
  • 文章
  • 专栏
全部文章

iframe-resizer 自动解析 iframe 高度

发布于 2022-04-30更新于 2023-04-08约 3 分钟

使 iframe 的高度和宽度的自动调整大小

  • https://www.npmjs.com/package/iframe-resizer
  • https://www.npmjs.com/package/iframe-resizer-react

被引用的 iframe 页面,需要引入该文件:

https://raw.githubusercontent.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js

引用方使用:

import IframeResizer from 'iframe-resizer-react'

<IframeResizer
  log
  src="http://anotherdomain.com/iframe.html"
  style={{ width: '1px', minWidth: '100%'}}
/>

高度控制,根据 heightCalculationMethod 字段判断:

  • bodyOffset uses document.body.offsetHeight
  • bodyScroll uses document.body.scrollHeight
  • documentElementOffset uses document.documentElement.offsetHeight
  • documentElementScroll uses document.documentElement.scrollHeight
  • max takes the largest value of the main four options
  • min takes the smallest value of the main four options
  • lowestElement Loops though every element in the the DOM and finds the lowest bottom point †
  • taggedElement Finds the bottom of the lowest element with a attributedata-iframe-height

https://github.com/davidjbradshaw/iframe-resizer/blob/master/docs/parent_page/options.md

<IframeResizer
  src="http://anotherdomain.com/iframe.html"
  style={{ width: '1px', minWidth: '100%'}}
  heightCalculationMethod="lowestElement"
/>

如果以上判断还是无效,可以通过被引用的 iframe 页面,设置 iframe 的参数:

<script>
  let dom = document.querySelector('.test')
  window.iFrameResizer = {
    heightCalculationMethod: function(){
        return dom.offsetHeight
    }
  }
</script>
<script src="js/iframeresizer.contentwindow.js"></script>

本文收录于专栏

一些好用的 npm 前端开源库

收集一些好用的前端开源库,主要是 npm 包

0 篇文章更新于 2026-08-17
上一篇VSCode 常用操作、设置与插件下一篇通过 wechat-format 把 markdown 转换为微信公众号格式,并将样式同步到博客前台

©2015-2026 黑白梦 粤ICP备15018165号

联系: heibaimeng@foxmail.com