场景描述:不使用我们常用的页面跳转属性【href】来实现跳转,也就是说没有新的html文件来供给【href】跳转使用,但却还要实现整个页面的内容替换。事实上本文要说的单页面应用也是和局部的内容切换类似,同样利用页面DOM元素的CSS中的【display】属性的none和block属性值来控制隐藏和显示。但当新的页面没有返回按钮时,还需要和浏览器的返回按钮实现绑定,则需要用到history对象的pushstate方法和popstate的监听方法。
此案例的优势:
1.在第一次打开页面时加载全部的dom和样式属性,此后切换页面时由于第一次已经加载,切换会非常迅速,延迟很小。
2.解决了跳转之后的页面没有返回前一页的相关按钮无法返回的问题
3.如果页面有和后端进行数据的动态获取,也会在第一次进入页面时发送请求并且进行渲染,避免了操作网页时多次发送请求,导致网页数据渲染加载慢的问题。
4.跳转后的地址栏可以由开发人员在前页面地址最后自定义加上新的符号,如“New.html#跳转后的页面名称”,#号也可以改为其他符号。
缺点:
在和后端进行巨大数据量交互时,一次性发送请求获取所有接口的数据,等待数据时间过长,不适用于大并发量的网页。各位朋友根据自己页面的情况酌情使用。
话不多说,来一个简单的案例予以展示。
<div class="content1">页面1</div>
<button class="skip">跳转</button>
<div class="content2">页面2</div>
<div class="select">默认选中</div>
* {
margin: 0;
padding: 0;
}
.content1 {
width: 100vw;
height: 100vh;
background-color: aqua;
font-size: 40px;
line-height: 100vh;
text-align: center;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
}
.skip {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 50px;
background-color: gray;
border-radius: 4px;
}
.content2 {
width: 100vw;
height: 100vh;
background-color: hotpink;
font-size: 40px;
line-height: 100vh;
text-align: center;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
display: none;
}
.select {
width: 200px;
height: 50px;
text-align: center;
line-height: 50px;
background-color: gray;
position: absolute;
top: 30px;
left: 50px;
display: none;
}
var Cont1 = document.querySelector(".content1");
var Cont2 = document.querySelector(".content2");
var Sel = document.querySelector(".select");
var Obtn = document.querySelector(".skip");
Sel.onfocus = function () {
this.style.boxShadow = "0 0 5px 5px #fff";
}
Obtn.onclick = function () {
Cont1.style.display = "none";
Cont2.style.display = "block";
Sel.style.display = "block";
var state = "新增的state";
window.history.pushState(state, "", "#foward");
Sel.onfocus();
}
window.addEventListener('popstate', function (event) {
// var state = "后退之后的state"
// window.history.replaceState(state, '', '');
Cont1.style.display = "block";
Cont2.style.display = "none";
Sel.style.display = "none";
}, false);