将想法与焦点和您一起共享

Iframe跨域自适应高度(兼容IE/Firefox)终极解决方案发布者:本站     时间:2020-05-16 08:05:48

Iframe跨域自适应高度(兼容IE/Firefox)终极解决方案

main.html在A域,被包含的iframe.html、proxy.html以及proxy.js在B域

main.html

<script type="text/javascript" src="http://zhaohe162.blog.163.com/blog/B域/proxy.js"></script>

<script type="text/javascript">

var aai=new AutoAdjustIframe();

aai.autoAdjust('frameName');

</script>

<div style="border:1px solid#ccc;padding:10px;">

<iframe id="frameName" name="frameName" src="http://zhaohe162.blog.163.com/blog/B域/iframe.html?hostname=192.168.1.100:8080" style="width:100%;border:1px solid#f00;" scrolling="no" frameborder="0"></iframe>

</div>

<br/>尾部<br/>

iframe.html

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

<script type="text/javascript" src="http://zhaohe162.blog.163.com/blog/proxy.js"></script>

<script type="text/javascript">

var aai=new AutoAdjustIframe();

aai.setHash();

</script>

proxy.html

B域一个空白页面,防止404

proxy.js

var AutoAdjustIframe=function(){

var autoSecond=1;

this.autoAdjust=function(iframeId){

setInterval(function(){

try{

var height=parseFloat(window.frames[iframeId].frames[iframeId+'-proxyiframe'].location.hash.replace(/^#/,''))||100;

document.getElementById(iframeId).style.height=height+'px';

}catch(e){};

},autoSecond);

};

var getHeight=function(){

return Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,

document.documentElement.clientHeight,document.body.clientHeight);

};

/*

*设置代理页的hash值,需要A域传给B域hostname

*/

this.setHash=function(){

var aSearch=document.location.search.match(/hostname=([^&]+)/);

if(!!aSearch){

//设定代理页面url

var proxyUrl='http://'+aSearch[1]+'/proxy.html';

var height=getHeight();

try{

console.log('proxyUrl:'+proxyUrl+'\nThe Iframe\'s height:'+height);

}catch(e){};

//生成代理iframe

var iframe=document.createElement('iframe');

iframe.src=proxyUrl+'#'+height;

iframe.id=window.name+'-proxyiframe';

iframe.name=window.name+'-proxyiframe';

iframe.style.display='none';

document.body.appendChild(iframe);

//动态设置代理iframe的hash,以便重新获取新的高度

var interval=setInterval(function(){

if(getHeight()!=height){

height=getHeight();

iframe.src=proxyUrl+'#'+height;

try{

console.log('Reloading,The Iframe\'s height:'+height);

}catch(e){};

}

},autoSecond);

}

};

};



选择我们,优质服务,不容错过
1. 优秀的网络资源,强大的网站优化技术,稳定的网站和速度保证
2. 15年上海网站建设经验,优秀的技术和设计水平,更放心
3. 全程省心服务,不必担心自己不懂网络,更省心。
------------------------------------------------------------
24小时联系电话:021-58370032