来源:http://www.mzone.cc/article/457.html
[转载声明] 转载时必须标注:本文来源于铁木箱子的博客http://www.mzone.cc
[本文地址] 本文永久地址是: http://www.mzone.cc/article/457.html
[本文地址] 本文永久地址是: http://www.mzone.cc/article/457.html
iframe一般在我们用来最大和最麻烦的就是自动高度调整了,这里结合铁木箱子的实际使用情况,给出一个javascript代码片段和测试例子。
1、mzone.cc.js文件,用来创建基于命名空间的对象
-
/**
-
* Title : 基于命名空间的js对象创建
-
* Author : 铁木箱子
-
* Site : http://www.mzone.cc
-
* Date : 2010-10-14
-
* Version : 0.1
-
*/
-
-
function mzone
(
)
{
}
;
-
-
/**
-
* Desc : 使用给定的对象路径进行对象的创建
-
* Para : objPath - 对象路径,字符串类型,格式为:xx.yy.zz
-
* Return : 没有返回值,创建成功后直接使用对象路径即可
-
*/
-
mzone.
createObject
=
function
(
/*string*/objPath
)
{
-
if
(
!objPath
||
typeof
(objPath
)
!=
'string'
)
return
;
-
var root
= window
;
-
var parts
= objPath.
split
(
'.'
)
;
-
for
(
var i
=
0
; i
< parts.
length
; i
++
)
{
-
if
(
typeof
(root
[parts
[i
]
]
)
==
'undefined'
) root
[parts
[i
]
]
=
{
}
;
-
root
= root
[parts
[i
]
]
;
-
}
-
}
;
2、mzone.cc.iframe.js文件,iframe的自动高度调整
-
/**
-
* Title : iframe高度自动调整,适应各个浏览器(IE、Firefox、Chrome等).需要注意的是在chrome下测试时必须在web容器中测试
-
* Author : 铁木箱子
-
* Site : http://www.mzone.cc
-
* Date : 2010-10-14
-
* Version : 0.1
-
*/
-
-
/**
-
* Desc : 创建mzone.cc.iframe对象
-
*/
-
mzone.
createObject
(
"mzone.cc.iframe"
)
;
-
-
/**
-
* Desc : 定义对象mzone.cc.iframe的静态方法实现iframe动态调整
-
* Para : iframe - 要调整的iframe对象,DOM对象
-
* extHeight - 自动计算iframe的高度后额外增加的高度值,数字型
-
* minHeight - iframe的最小高度,数字型
-
* Return : 没有返回值
-
*/
-
mzone.
cc.
iframe.
autoHeight
=
function
(
/*object*/iframe
,
/*int*/extHeight
,
/*int*/minHeight
)
{
-
iframe.
style.
display
=
"block"
;
-
if
(iframe.
contentDocument
&& iframe.
contentDocument.
body.
offsetHeight
)
{
// ff,chrome等
-
var h
= parseInt
(iframe.
contentDocument.
body.
offsetHeight
)
+
50
;
-
h
+= extHeight
;
-
if
(h
< minHeight
) h
= minHeight
;
-
iframe.
height
= h
+
"px"
;
-
}
else
if
(iframe.
Document
&& iframe.
Document.
body.
scrollHeight
)
{
// IE
-
var h
= parseInt
(iframe.
Document.
body.
scrollHeight
)
+
35
;
-
h
+= extHeight
;
-
if
(h
< minHeight
) h
= minHeight
;
-
iframe.
height
= h
+
"px"
;
-
}
else
{
-
var h
= parseInt
(iframe.
contentWindow.
document.
documentElement.
scrollHeight
)
+
35
;
-
h
+= extHeight
;
-
if
(h
< minHeight
) h
= minHeight
;
-
iframe.
height
= h
+
"px"
;
-
}
-
}
将以上两个js保存并引入到页面中就可以按照如下方法调用实现iframe的高度自动调整了:
-
var iframe
= document.
getElementById
(
"iframe_body"
)
;
// iframe对象
-
var extHeight
=
0
;
// 要额外增加的iframe的高度值
-
var minHeight
=
300
;
// iframe的最小高度设置
-
mzone.
cc.
iframe.
autoHeight
(iframe
, extHeight
, minHeight
)
;
以上脚本在IE、Firefox和Chrome下都测试通过,需要注意的是在google的Chrome浏览器中离线测试时是有错误的,需要在web容器(如apache或IIS)中进行测试才能够看到效果。