让动态的 iframe 内容高度自适应

您所在的位置:网站首页 jquery获取iframe内容高度 让动态的 iframe 内容高度自适应

让动态的 iframe 内容高度自适应

2024-04-13 15:09| 来源: 网络整理| 查看: 265

使用iframe加载其他页面的时候,需要自适应iframe的高度

 

这里加载了两个不同内容高度的页面至iframe中

 

1. 没有设置高度   

默认长这样

有滚动条,可以看到iframe并不会因为内容高度自动撑开

 

2. 显示地设置高度

内容长这样,但可以看到,高度定死了,没有自适应

 

3. 在onload事件触发时,根据body的高度自适应iframe的高度

注意到这里的 this.contentWindow 其实就类似与下方的 name值对应的iframe2,两种引用方式是等价的

可以发现,高度虽然能自适应,不过只支持高度了“从小到大”的自适应

如iframe2的内容比iframe1的高,后者动态加载出前者能自适应,但前者动态加载出后者就不行了,这种高度减小不了

 

最后的解决办法是

4. 在onload事件中动态设置高度为body高度之前,先将原高度还原为auto或空值

可以用setTimeout(fn,0)将高度设置放到下一轮事件循环中执行,或者在 onbeforeunload 事件中先把高度设置为auto

setTimeout

  var iframes = document.getElementsByTagName('iframe'); for (var i = 0, j = iframes.length; i < j; ++i) { // 放在闭包中,防止iframe触发load事件的时候下标不匹配 (function(_i) { iframes[_i].onload = function() { // 提前还原高度 this.setAttribute('height', 'auto'); // 或设为'' // 再在下一轮事件循环中设置新高度 setTimeout(function() { iframes[_i].setAttribute('height', iframes[_i].contentWindow.document.body.scrollHeight); }, 0); } })(i); }

onbeforeunload

var iframes = document.getElementsByTagName('iframe'); for (var i = 0, j = iframes.length; i < j; ++i) { // 放在闭包中,防止iframe触发load事件的时候下标不匹配 (function(_i) { iframes[_i].onload = function() { this.contentWindow.onbeforeunload = function() { iframes[_i].setAttribute('height', 'auto'); }; this.setAttribute('height', this.contentWindow.document.body.scrollHeight); }; })(i); }

基本ok了,不过偶尔(可能是电脑卡了?)会看到些抖动闪动的情况

 

5. 要避免这个情况,可暂时将它隐藏

先设置display为none,再设置为block;或者先设置visibility为hidden,再设置为visible 。 用visibility看起来变化地更自然一点

setTimeout

var iframes = document.getElementsByTagName('iframe'); for (var i = 0, j = iframes.length; i < j; ++i) { // 放在闭包中,防止iframe触发load事件的时候下标不匹配 (function(_i) { iframes[_i].onload = function() { this.style.visibility = 'hidden'; // this.style.display = 'none'; // 提前还原高度 this.setAttribute('height', 'auto'); // 或设为'' // 再在下一轮事件循环中设置新高度 setTimeout(function() { iframes[_i].setAttribute('height', iframes[_i].contentWindow.document.body.scrollHeight); iframes[_i].style.visibility = 'visible'; // iframes[_i].style.display = 'block'; }, 0); } })(i); }

onbeforeunload

var iframes = document.getElementsByTagName('iframe'); for (var i = 0, j = iframes.length; i < j; ++i) { // 放在闭包中,防止iframe触发load事件的时候下标不匹配 (function(_i) { iframes[_i].onload = function() { this.contentWindow.onbeforeunload = function() { iframes[_i].style.visibility = 'hidden'; // iframes[_i].style.display = 'none'; iframes[_i].setAttribute('height', 'auto'); }; this.setAttribute('height', this.contentWindow.document.body.scrollHeight); this.style.visibility = 'visible'; // this.style.display = 'block'; }; })(i); }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3