www.a.com 域下面index.html嵌入www.b.com 域下的content.html页面,此页面会动态变化。要求:html
现有主界面index.html在域a下,被嵌套页面content.html在域b下,被嵌套页面content.html又嵌套一个在域a下的代理页面agent.html。当用户打开浏览器访问index.html的时候载入content.html,触发content.html的onload事件获取其自身高度,而后content.html载入agent.html并将高度值做为参数赋值给agent.html的location对象。这样agent.html就能够经过location.hash得到content.html的高度,而后将获取到的content.html的高度传给index.html,而后修改content.html的高度。 jquery
在a域 index.html页面嵌入iframe浏览器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>主页</title> </head> <body> <div style="border-top: 1px #ccc solid; margin: 10px 0px;" id="J_ContentWrap"> <iframe src="http://www.b.com/content.html" id="J_Content" width="100%" scrolling="no" frameborder="0"></iframe> </div> </body> </html>
在b域 content.html页面嵌入iframe,src设置为a域的代理页面agent.html,当content.html页面内容动态变化时改变此iframe的src。实现将高度传递给a域。缓存
function sethash(height){ var hashH; if(height != null || height != undefined){ hashH = height; } else{ hashH = $(document.body).outerHeight(true); } if(document.getElementById("J_Agent")){ $("#J_Agent").attr('src','http://www.a.com/agent.html?t=' + new Date().getTime() + '#height=' + hashH); } else{ $("body").append('<iframe id="J_Agent" style="display:none;" frameborder="0" scrolling="no" ' + 'marginheight="0" marginwidth="0" ' + 'src="http://www.a.com/agent.html?t=' + new Date().getTime() + '#height=' + hashH + '" ></iframe>'); } } window.onload=sethash;
改变src值时添加app
?t=' + new Date().getTime()
是为了防止浏览器缓存不能及时的改变iframe大小,页面高度是有参数height=hashH
传递的。spa
在agent.html页面获取height参数,动态设置index.html中iframe的高度,也可在height==0是隐藏iframe或者外层div.代理
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>代理页面</title> </head> <script> function pseth(){ var iObj = parent.parent.document.getElementById('J_Content'); var hash = window.location.hash.slice(1); if (hash && /height=/.test(hash)) { //iframe中没有内容是参数为0,则隐藏iframe或者外层div var height = hash.replace("height=", ""); if(height == 0){ parent.parent.document.getElementById("J_ContentWrap").style.display = "none"; } else{ iObj.height = height; } } } pseth(); </script> </body> </html>
获取content.html页面的高度,在获取高度时无论是用document.documentElement.scrollHeight
仍是document.body.scrollHeight
均存在浏览器兼容性问题。这是强大的jquery帮助了咱们,$(document.body).outerHeight(true)
code