模拟在单个页面,默认隐藏content2内容,点击Next,往浏览器添加一条历史记录,点击浏览器的【后退】按钮,显示回content1内容。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.container {
width: 750px;
margin: 0 auto;
border: 1px solid black;
}
.content1 {
height: 300px;
border: 1px solid red;
text-align: center;
line-height: 300px;
color: white;
background-color: blue;
position: relative;
}
.content2 {
height: 300px;
border: 1px solid red;
text-align: center;
line-height: 300px;
color: white;
background-color: brown;
display: none;
}
.nexnBtn {
width: 40px;
height: 20px;
line-height: normal;
position: absolute;
bottom: 10px;
right: 10px;
background-color: cornflowerblue;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
this is content1
<span class="nexnBtn">Next</span>
</div>
<div class="content2">
this is content2
</div>
</div>
</body>
<script type="text/javascript">
window.onload = function() {
var nexnBtn = document.getElementsByClassName("nexnBtn")[0];
nexnBtn.addEventListener("click", function() {
console.log("click")
//添加历史记录
window.history.pushState("", "", "");
var content2 = document.getElementsByClassName("content2")[0];
content2.style.display = 'block';
nexnBtn.parentElement.style.display = 'none';
});
}
window.addEventListener("popstate", function(e) {
var content2 = document.getElementsByClassName("content2")[0];
if(content2.style.display == 'block') {
content2.style.display = 'none';
}
var content1 = document.getElementsByClassName("content1")[0];
content1.style.display = 'block';
});
</script>
</html>
效果:
点击Next按钮后;
点击【回退】按钮将显示回content1内容。