-
iframe跨域高度自适应(超完美) - [Javascript]2009-11-26
功能:只要按照以下方法,便可轻松实现iframe跨域高度自适应。且还可以由此延伸其它用途,这些就靠大家天马行空的想像了。
实例:A(dev.net)域加载B(dev2.net)域iframe页面,此iframe页面要实现高度自适应。
文件:A域中a.html,proxy.js,proxy.html,B域中b.html,C域(好比图片服务器)中proxy.js
按以上3域的模式分布文件,便可轻松应对多级系统的问题。1、a.html
<iframe autoH='yes' id="aiframe" name="aiframe" src="http://dev2.net/b.html?proxy=http://dev.net/proxy.html" style="width:100%;border:1px solid #f00;" scrolling="no" frameborder="0"></iframe>
2、proxy.html
<script type="text/javascript">
(function(){
function changeIframeSize(){
//主域iframeName
var mainName=window.name.replace(/_iframe$/,'');
//主域iframeNode
var mainNode=parent.parent.document.getElementById(mainName);
if(mainNode.getAttribute('autoH')=='yes'){
mainNode.style.height=document.location.hash.replace(/^#/,'')+'px';
}}
changeIframeSize();
})();
</script>3、b.html
页面底部加入:
<script type="text/javascript" src="http://dev3.net/proxy.js"></script>
4、proxy.js
(function(){
function setIframeHash(){
var searchArr=document.location.search.match(/proxy=([^&]+)/);
if(!!searchArr){
//设定代理页面url
var proxyUrl=searchArr[1];
var height=document.documentElement.scrollHeight;
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+'_iframe';
iframe.name=window.name+'_iframe';
iframe.style.display='none';
document.body.appendChild(iframe);
//动态设置代理iframe的hash,以便重新获取新的高度
var interval=setInterval(function(){
if(document.documentElement.scrollHeight!=height){
height=document.documentElement.scrollHeight;
iframe.src=proxyUrl+'?rnd='+Math.random()+'#'+height;
try{
console.log('Reloading,The Iframe\'s height:'+height);
}catch(e){};
}
},1);
}
}
setIframeHash();
})();















