Home  >  Article  >  Web Front-end  >  Iframe 自适应高度并实时监控高度变化的js代码_javascript技巧

Iframe 自适应高度并实时监控高度变化的js代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:42:491022browse

google N次 + 百度M次 + 试验了1605次之后(听说农药1605就是实验了这么多次后出来的),得出下面成果,在IE7及Firefox3里试了下还能凑合着用用!
1、首先给出个Iframe。

复制代码 代码如下:



2、然后看看怎么获取Iframe中的页面的高度。
其实最麻烦的就是怎么让获取的高度准确,不同的方式不同的浏览器中获取到的值都会不一样!晕啊~~。参考了多方意见得出以下javascript函数(doc参数为window.document对象):
复制代码 代码如下:

function getDocHeight(doc)
{
//在IE中doc.body.scrollHeight的可信度最高
//在Firefox中,doc.height就可以了
var docHei = 0;
var scrollHei;//scrollHeight
var offsetHei;//offsetHeight,包含了边框的高度
if (doc.height)
{
//Firefox支持此属性,IE不支持
docHei = doc.height;
}
else if (doc.body)
{
//在IE中,只有body.scrollHeight是与当前页面的高度一致的,
//其他的跳转几次后就会变的混乱,不知道是依照什么取的值!
//似乎跟包含它的窗口的大小变化有关
if(doc.body.offsetHeight) docHei = offsetHei = doc.body.offsetHeight;
if(doc.body.scrollHeight) docHei = scrollHei = doc.body.scrollHeight;
}
else if(doc.documentElement)
{
if(doc.documentElement.offsetHeight) docHei = offsetHei = doc.documentElement.offsetHeight;
if(doc.documentElement.scrollHeight) docHei = scrollHei = doc.documentElement.scrollHeight;
}
/*
docHei = Math.max(scrollHei,offsetHei);//取最大的值,某些情况下可能与实际页面高度不符!
*/
return docHei;
}

3、最后修改Iframe的高度,并用一个定时器来不间断检查它包含的页面的高度变化。
复制代码 代码如下:

function doReSize()
{
var iframeWin = window.frames['ifrm'];
var iframeEl = window.document.getElementById? window.document.getElementById('ifrm'): document.all? document.all['ifrm']: null;
if ( iframeEl && iframeWin )
{
var docHei = getDocHeight(iframeWin.document);
if (docHei != iframeEl.style.height) iframeEl.style.height = docHei + 'px';
}
else if(iframeEl)
{
var docHei = getDocHeight(iframeEl.contentDocument);
if (docHei != iframeEl.style.height) iframeEl.style.height = docHei + 'px';
}
}
function runResizeTask()
{
doReSize();
setTimeout("runResizeTask()",500);//每隔半秒执行一次
}
runResizeTask();

在这里就没有去考虑被包含的页面中是否有折叠、隐藏/展现的情况了!
完整js代码
复制代码 代码如下:



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn