Iframe高度自适应的方法(跨域及非跨域)

本文介绍了两种实现Iframe高度自适应的方法:一种适用于跨域场景,通过利用window.clipboardData进行父窗体与子窗体间的通信;另一种适用于非跨域场景,直接通过JavaScript修改Iframe的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:支持跨域的Iframe高度自适应
主页面A.html : 注意下面代码中加粗的部分
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html  xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta  http-equiv ="Content-Type"  content ="text/html; charset=gb2312"   />
< title > 无标题文档 </ title >
< script  language ="javascript"  type ="text/javascript"  src ="js/TabPage.js" ></ script >
< link  href ="css/main.css"  rel ="stylesheet"  type ="text/css"   />
< script >
function resetIframeHeight(){
try{
var str=window.clipboardData.getData('text');
var obj=document.getElementById('chezuo');
if(str.match(/^frameHeight=d+$/)){
obj.style.height
=parseInt(str.match(/d+/))+'px';
window.clipboardData.setData(
'text','null');
}

}
catch(e){}
setTimeout(resetIframeHeight,
100);
}

</ script >
</ head >

< BODY  leftMargin =0  topMargin =0  marginheight ="0"  marginwidth ="0"  onLoad ="resetIframeHeight();">
< center >
AAAAAAAAAAAAAAAAAAAAA
< IFRAME   name ="chezuo"  id ="chezuo"  SRC ="B.html"  allowTransparency ="false"  WIDTH ="800"  HEIGHT ="800"  align ="center"  border ="0"  frameborder ="0"  scrolling ="no"  cellpadding ="0"  cellspacing ="0"  style ="font-size: 9pt"  target ="_self" ></ IFRAME >

</ center >
</ body >
</ html >
 
B.html
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< HTML >
    
< HEAD >
        
< title ></ title >
        
< meta  http-equiv ="Content-Type"  content ="text/html; charset=gb2312" >         
    
</ HEAD >
    
< body >         
        
< script  src ="js/a.js"></ script > 注意引用JS的位置必须在<body>里面
            
< center >
                BBBBBBBBBBBBBBBBBBBBBBB
            
</ center >        
    
</ body >
</ HTML >

a.js的内容如下:

document.body.onload  =  jxh;
function  jxh()
{
    window.clipboardData.setData(
'text',String('frameHeight='+document.body.scrollHeight));

}

方法二:非跨域的IFRAM高度自适应
主页面使用如下语句引用IFRAME页面:
< iframe  name ="ifrName"  src ="targetName.htm"  frameborder =false  scrolling ="auto"  width ="100%"  height ="100%"  frameborder =no  onload ="document.all['ifrName'].style.height=ifrName.document.body.scrollHeight"   ></ iframe >  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值