iframe-auto-height

自动调整 iframe 的高度,主要用于商业项目的微访谈页面。

Usage no npm install needed!

<script type="module">
  import iframeAutoHeight from 'https://cdn.skypack.dev/iframe-auto-height';
</script>

README

iframe auto height

自动调整 iframe 的高度,主要用于商业项目的微访谈页面。

该模块会处理页面所有的 iframe,因此,即便页面上有多个 iframe 也没有问题。

示例:Demo

浏览器兼容性

iframe 之间的通信使用了 postMessage API,该 API 最低兼容到 IE8

用法

需要分别在 iframe 页面(即 child 页面)和引入 iframe 的页面(即 parent 页面)中调用 new AutoHeightChild()new AutoHeight() 为完成初始化操作。

P.S. 上面之所以用 new,是为了兼容旧版本的代码,统一风格。

具体到商业项目中,child 页面(即丁香客微访谈页面)中已经引入了该模块,我们所要做的只是在商业 项目中引入该模块,然后调用 new AutoHeight() 即可。

如何安装

方法一:使用 npm 安装(推荐)

该模块已经发布到了 npm,可以通过下面的命令进行安装:

npm i iframe-auto-height --save

调用方法:

  1. child 页面:
// 这一步需要在 iframe 页面中操作,丁香客页面中已经完成了这一步,无需我们操作
var AutoHeightChild = require('iframe-auto-height/child');
new AutoHeightChild();
  1. parent 页面:
// 这一步是需要我们添加到商业项目中的
var AutoHeight = require('iframe-auto-height/parent');
new AutoHeight();

方法二:使用 <script>$.getScript() 引入

  1. child 页面
<script src="http://assets.dxycdn.com/third-party/AutoIframeHeight/2.0/child-min.js"></script>
<script>
new AutoHeightChild();
</script>
  1. parent 页面
<script src="http://assets.dxycdn.com/third-party/AutoIframeHeight/2.0/parent-min.js"></script>
<script>
new AutoHeight();
</script>

同样,你也可以使用 $.getScript() 方法来动态加载脚本。

开发

  1. Clone 本项目
  2. 运行 npm install
  3. 修改代码
  4. 测试没有问题后,发布到 npm 上
  5. 复制 dist 目录中所有的 JS 文件到 svn 目录 assets/third-party/AutoIframeHeight/2.0 中,并 发布到线上

注:步骤 4 发布到 npm 上时需要运行 npm version major|minor|patchnpm publish 这两个命令, 具体如何使用请参考 npm 的官方文档

其他

注:下面解释的这种情况仅做了解,一般不会这样使用。

如果通过 npm 安装后直接使用 require('iframe-auto-height') 来加载该模块的话会返回一个包含 ParentChild 属性的对象,即:

var iframeAutoHeight = require('iframe-auto-height');

console.log(iframeAutoHeight.Child); // 等同于 AutoHeightChild
console.log(iframeAutoHeight.Parent); // 等同于 AutoHeight

同样,相应的还可以通过 <script> 来引入 http://assets.dxycdn.com/third-party/AutoIframeHeight/2.0/standalone-min.js

这样会在 window 上添加一个全局变量 IframeAutoHeight,它里面包含 ParentChild 两个属性。 用法和上面类似。

CHANGELOG

LICENSE

MIT