场景描述:页面中实现整个页面的内容的替换,但是不使用我们常用的页面【跳转】,【跳转】也就不符合单页面的诉求。事实上单页面的内容切换也是和局部的内容切换一样,同样使用页面DOM元素的CSS属性中的【显示】和【隐藏】来控制。但当新的页面没有返回按钮时,就需要和浏览器的按钮实现绑定,则需要用到history对象的pushstate方法和popstate的监听方法。话不多说,来一个简单的案例予以展示。
<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);版权声明:本文为weixin_54373461原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。