現在有個項目是webapp,通過iframe加載第三方資源,除了主入口index.jsp(java編譯之後)和3個活動的html頁面,剩下都是通過主頁面裏的iframe進行src的跳轉。
1.ifarme加載頁面後的高度問題:
主入口iframe加載本地頁面比如main.html的是可以撐開的,如果加載第三方是不能撐開的,除非給主頁面裏的iframe加上固定高度,或者通過js計算移動設備的高度,給到主頁面裏的iframe上邊,代碼如下:
var hg = window.screen.height;
$(".iframe-content").css("height",hg+"px");
同時最好給主頁面裏的iframe
width="100%" height="100%"
2.頁面滑動時,滑動的內容實際上是iframe加載的頁面在滑動,不論是本地的main.html還是加載的第三方頁面,如果你想用滑動高度做點什麼,請用一下代碼
window.onscroll=function(){
var top = document.body.scrollTop;
console.log( top )
$('.aaa').css({
top : $(parent.window).scrollTop()+300
});
}
3.蘋果機出現無法滑動的情況,請用以下代碼
.iphone{
-webkit-overflow-scrolling:touch;
overflow:auto;
height:100%;
}
4.頁面中iframe的跳轉實際上是它的srcs屬性在變化:
function loadTabUrl(goUrl,hpx){
alert(goUrl);
$("#external-frame").attr("src",goUrl);
}
這樣存在倆種情況:1)通過一個iframe不斷加載其他頁面,如上;
2)外鏈出去,如下:
window.top.location.href = goUrl;
5.在外部獲取iframe加載頁面的元素並操作
<body>
<div class="iframe-content">
<iframe src="main.html" name="myiframe" onload="goTop()" width="100%" height="100%" frameborder="0" id="external-frame" class="iphone"
></iframe>
</div>
<div style="width: 50px;height: 50px;background: blue;position: fixed;top: 500px;left: 0;"></div>
<script>
var win = document.getElementById('external-frame').contentWindow;
win.onscroll=function(){
var top = win.document.body.scrollTop;
console.log(top)
$(window.frames["myiframe"].document).find(".aaa").css({
top: 300
})
}
var hg = window.screen.height;
$(".iframe-content").css("height",hg+"px");
</script>
</body>
通過上面的代碼我們可以獲得Id('external-frame')iframe加載的main.html裏面的一個class="aaa"的div元素,並且在頁面華東的時候,去控制它的css。
6.在iframe加載頁面的內部獲取父頁面的元素並操作
$(function() {
//在iframe中查找父頁面元素
alert($('#default', window.parent.document).html());
//在iframe中調用父頁面中定義的方法
parent.getHelloWorld();
//在iframe中調用父頁面中定義的變量
alert(parent.hello);
});
7.iframe加載的頁面與瀏覽器歷史記錄
iframe.contentWindow.location.replace(url) 這個在iframe裏跳轉頁面是不會有歷史記錄的
iframe.contentWindow.src = url; 這個會留下歷史記錄
window.history.pushState()方法用於新添加一條歷史記錄例如:
window.history.pushState({}, null, 'a.html');
第一個參數和第二個參數可以傳入null,第三個參數就是需要變成的url地址,值得一提的是,這個地址必須是同源的。第一個參數可以放入一個對象,瀏覽器會將此對象變量標記到這個歷史記錄中,當從別的頁面再次回到這個頁面的時候,瀏覽器調用onpopstate
事件將此變量當成參數傳入。
Firefox:
如果iframe是靜態存在在HTML中時,iframe的任何src或者location改變都會被記錄到瀏覽器history中。
如果iframe是在頁面加載完成後動態創建的,那麼iframe的任何src或者location改變都不會被記錄到瀏覽器history中。
IE:
兩種iframe的src或者location改變都會被記錄到瀏覽器history中。
Safari:
兩種iframe的src或者location改變都不會被記錄。