<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#menu {
list-style: none;
margin: 0;
padding: 0;
position: relative;
height: 200px;
}
#menu>li {
float: left;
margin-left: 20px;
padding: 10px 30px;
border: 1px solid #000000;
}
ul:not(#menu) {
position: absolute;
display: none;
}
</style>
</head>
<body>
<ul id="menu">
<li>水果</li>
<li>蔬菜</li>
<li>零食</li>
<li>饮料</li>
</ul>
<ul id="list1">
<li>猕猴桃</li>
<li>苹果</li>
<li>梨</li>
</ul>
<ul id="list2">
<li>白菜</li>
<li>土豆</li>
<li>地瓜</li>
</ul>
<ul id="list3">
<li>辣条</li>
<li>牛肉干</li>
<li>薯片</li>
</ul>
<ul id="list4">
<li>可乐</li>
<li>雪碧</li>
<li>果汁</li>
</ul>
<script>
var menu = document.getElementById("menu");
var lis = Array.from(menu.getElementsByTagName("li"));
var uls = Array.from(document.getElementsByTagName("ul")).slice(1);
window.onpopstate = function () {//当修改历史记录时,可以跳转到对应的历史记录
// console.log(history.state);
changeList();
}
for (var i = 0; i < lis.length; i++) {
lis[i].onclick = clickHandler
}
function clickHandler() {
var index = lis.indexOf(this);
history.pushState({ state: "list" + (index + 1) }, "", "#list" + (index + 1));//这里只能改变锚点,不能跳转锚点
changeList();//跳转锚点
}
function changeList() {
for (var i = 0; i < uls.length; i++) {
if (uls[i].id === history.state.state) {
uls[i].style.display = "block";
} else {
uls[i].style.display = "none";
}
}
}
</script>
</body>
</html>
使用history.state不刷新页面
最新推荐文章于 2024-10-06 12:29:00 发布