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