现在的位置: 首页 > 综合 > 正文

iframe自适应内层页面高度,可响应页面中折叠点击事件,以及实现跨域的问题解决方案

2012年09月12日 ⁄ 综合 ⁄ 共 1849字 ⁄ 字号 评论关闭

一、父页面和内容页在同一域名地址下的情况,页面发生点击事件后自动调节父页面高度[此方法不可实现跨域]

代码

<iframe id="iframe1" onload="addEvt(this)" src='[您的引用页面地址]'
 frameborder='0' marginheight='0' marginwidth='0' width='100%' height='600px'
scrolling='no'></iframe>

<script type="text/javascript">
function addEvt(ifr) {
var doc = ifr.contentWindow.document;
doc.onclick
= function() {
ifr.style.height
= (document.all ? doc.body.scrollHeight :

doc.body.offsetHeight)
+ 'px';
}
ifr.style.height
= (document.all ? doc.body.scrollHeight :

doc.body.offsetHeight)
+ 'px';
}
</script>

二、iframe跨域的解决方案:

假设:我们要应用Iframe的页面为:a.html 域名为:www.a.com ; 要嵌入的页面为content.html;中间页面为iframe.html

a.html中的内容

<iframe id="iframe1" src='[引用页面地址]'
frameborder='0' marginheight='0' marginwidth='0' width='100%' height='600px'
scrolling='no'></iframe>

* 此时我们需要建立一个中间页面iframe.html,把这个文件放在www.a.com下,也就是和a.html在同一域名下的目录

iframe.html中的内容 

代码

<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("c_iframe"); //此处为content.html中iframe的ID
var hash_url = window.location.hash;
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
b_iframe.style.width
= hash_width;
b_iframe.style.height
= hash_height;
</script>

 

content.html中的内容

代码

<iframe id="c_iframe" height="0″ width="0″ src="http://www.a.com/iframe.htm" style="display:none" ></iframe>
<script type="text/javascript">
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = document.all ? document.body.scrollHeight : document.body.offsetHeight;
var c_iframe = document.getElementById("c_iframe");
c_iframe.src
= c_iframe.src + "#" + b_width + "|" + b_height;
</script>

 二、iframe中的页面有服务端事件出发后会改变页面长度:

在服务端执行完语句之后,执行JS事件改变长度:window.parent.autoHeight();

在父页面:

 function autoHeight() { 
        $("iframe").each(function() {
            var c = this.contentWindow.document;
            var ifrHeight = document.all ? c.body.scrollHeight : c.body.offsetHeight;
            if (parseInt(ifrHeight) != 0) {
                this.style.height = ifrHeight;
            }
        });
    }

抱歉!评论已关闭.