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
调用方法:
- child 页面:
// 这一步需要在 iframe 页面中操作,丁香客页面中已经完成了这一步,无需我们操作var AutoHeightChild = ;;
- parent 页面:
// 这一步是需要我们添加到商业项目中的var AutoHeight = ;;
<script>
或 $.getScript()
引入
方法二:使用 - child 页面
- parent 页面
同样,你也可以使用 $.getScript()
方法来动态加载脚本。
开发
- Clone 本项目
- 运行
npm install
- 修改代码
- 测试没有问题后,发布到 npm 上
- 复制
dist
目录中所有的 JS 文件到 svn 目录assets/third-party/AutoIframeHeight/2.0
中,并 发布到线上
注:步骤 4 发布到 npm 上时需要运行 npm version major|minor|patch
和 npm publish
这两个命令,
具体如何使用请参考 npm 的官方文档。
其他
注:下面解释的这种情况仅做了解,一般不会这样使用。
如果通过 npm 安装后直接使用 require('iframe-auto-height')
来加载该模块的话会返回一个包含 Parent
和 Child
属性的对象,即:
var iframeAutoHeight = ; console; // 等同于 AutoHeightChildconsole; // 等同于 AutoHeight
同样,相应的还可以通过 <script>
来引入
http://assets.dxycdn.com/third-party/AutoIframeHeight/2.0/standalone-min.js
。
这样会在 window
上添加一个全局变量 IframeAutoHeight
,它里面包含 Parent
和 Child
两个属性。
用法和上面类似。