如何让iframe高度自适应
目录
前言
今天有朋友问到我关于“iframe 自适应高度”的问题,原本以为是很简单的问题,没想到折腾了 20 分钟才搞定。期间遇到几个问题,要么是高度自适应了,但是当窗口改变时会出现滚动条。也就是当窗口放大时 iframe 没有自动跟随变大显得很小,或是当窗口缩小时 iframe 还是之前那么大就出现了滚动条。还有或是高度不准确,那么就达不到想要的效果了。
为什么需要使用 iframe 自适应高度呢?其实就是为了美观,要不然 iframe 和窗口长短大小不一,看起来总是不那么舒服,特别是对于我们这些编程的来说,如鲠在喉的感觉。
场景说明
- 有 A.html 与 B.html 两个页面;
- A.html 里包含了 B.html 的内容(B.html 通过 iframe 嵌套在 A.html 里,设 iframe 的 ID 为”iframe001″);
- B.html 的内容高度不固定;
- A.html 里包含 B.html 的 iframe 出现滚动条;
场景需求
让 A.html 页面里的 iframe 高度自适应,使之不出现滚动条;
一、JavaScript 代码
/** * iframe 服务 * @param {object} config 配置数据 */ let $IFrameService = function (config) { let $this = this; /** 创建配置 */ let $newConfig = function () { return { /** iframe 的 ID 列表(例如: ["frame1", "frame2"]) */ targetIds: [], }; }; /** * 读取相关配置 * @param {object} config 配置参数 */ let $loadConfig = function (config) { if (!config) { return $config; } if (config.targetIds) { $config.targetIds = config.targetIds; } return $config; }; /** 参数 */ let $config = $newConfig(); $config = $loadConfig(config); /** * 读取相关配置 * @param {object} config 配置参数 */ this.LoadConfig = function (config) { $loadConfig(config); return $this; }; /** 自适应高度 */ this.SetHeightFit = function () { let _config = { targetIds: [], }; if ($config) { _config.targetIds = $config.targetIds; } let _targetIds = _config.targetIds; let _iframes = new Array(); for (i = 0; i < _targetIds.length; i++) { if (document.getElementById) { let _iframe = document.getElementById(_targetIds[i]); _iframes[_iframes.length] = _iframe; if (!_iframe) { continue; } try { let _window = _iframe.contentWindow || _iframe.contentDocument.parentWindow; //console.log(_window) if (_window.document.body) { //console.log(_window.document.documentElement.scrollHeight); //console.log(_window.document.body.scrollHeight); _iframe.style.height = (_window.document.documentElement.scrollHeight || _window.document.body.scrollHeight) + 'px'; //console.log(_iframe.style.height); } } catch (ex) { console.log(ex); } } } return $this; }; /** 设置 iframe 的高度自适应 */ this.SetHeightAutoFit = function () { let _action = function () { if (!$this) { return; } $this.SetHeightFit(); }; setInterval(_action, 200); //if (window.addEventListener) { // window.addEventListener("load", _action, false); //} //else if (window.attachEvent) { // window.attachEvent("onload", _action); //} //else { // window.onload = _action; //} return $this; }; }; /** iframe 服务 */ var $iframeSvc = new $IFrameService();
二、如何使用
- 在 A.html 页面引用该 Js 文件;
- 加入以下 js 代码(在页面加载后执行):
$iframeSvc.LoadConfig({ targetIds: ['iframe001'] }).SetHeightAutoFit();
结语
以上就是如何让 iframe 高度自适应的方法,大家可以拿去使用啦。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 如何让iframe高度自适应
码云笔记 » 如何让iframe高度自适应