昨天码了一篇,结果一不小心手贱给关了,没保存,所以今天又补了一篇,下面进入正题。
现在的项目是给中国移动做的一个webapp,主要是加载第三方资源,暂时先用iframe,以后升级再补一篇。
1.加载第三方页面是position:fixed,滑动时会跳动的问题,就是在外面找到里面的元素进行动态赋值:
var win = document.getElementById('external-frame').contentWindow;
win.οnscrοll=function(){
var top = win.document.body.scrollTop;
console.log(top)
$(window.frames["myiframe"].document).find(".aaa").css({
top: 300
})
}
2.我查了下,window.history.pushState(url,null,url)方法,url必须同源,才能在window.onpopstate事件中检测到。但是现在有想要监听iframe不断加载后,浏览器的后退事件,怎么办呢?这里取个巧:
现在是上边7个tab,点击都会使下面静态的iframe标签的src属性发生变化,浏览器也会记录,但是返回时tab的选中状态是不变的,这是一个bug,代码如下;
点击时传入tab的index,即n
var state = { url:n }
setTimeout(function(){
window.history.pushState(state, null, "#" + goUrl);
},500)
点击后退按钮时,进行监听:
window.addEventListener("popstate", function(e) {
console.log("我监听到了浏览器的返回按钮事件啦");
window.history.go(-1);
var currentUrl = history.state.url;
$(".tabs li").eq(currentUrl).addClass("selected").siblings().removeClass("selected")
}, false);
ok,大部分工作完成了,但是还有个问题,当你只点击一次的时候是无法返回最开始首页的状态的,因为首页是刚刷新页面的时候加载的,并没有发生点击事件,它没有得到n值,它会报这个错
Uncaught TypeError: Cannot read property 'url' of null(…)
所以这样
<iframe src="main.html" οnlοad="goTop()" height="100%" frameborder="0" id="external-frame" ></iframe>
function goTop() {
$("body")[0].scrollIntoView();
var test = window.location.href;
var state = { url:0 }
setTimeout(function(){
window.history.replaceState(state, null, "#" + test);
},500)
}
window.addEventListener("popstate", function(e) {
console.log("我监听到了浏览器的返回按钮事件啦");
var currentUrl = history.state.url;
if(currentUrl == 0){
window.history.go(-1);
$(".tabs li").eq(0).addClass("selected").siblings().removeClass("selected");
}else{
window.history.go(-1);
$(".tabs li").eq(currentUrl).addClass("selected").siblings().removeClass("selected");
}
}, false);
这样就可以了
总之,iframe bug多多,大家尽量少用。前端的js框架其实就可以做跨域,像vue之类的。。。