现在有个项目是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改变都不会被记录。