首先我们上效果图:
我们第一步制作html和css部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.wrep {
width: 400px;
height: 400px;
}
.top {
width: 400px;
height: 50px;
line-height: 50px;
background-color: aquamarine;
}
.tab {
float: left;
width: 80px;
text-align: center;
}
.ta {
background-color: rgb(0, 207, 17);
color: #fff;
}
.tap {
width: 400px;
height: 350px;
line-height: 350px;
background-color: rgb(0, 207, 17);
color: #fff;
text-align: center;
}
</style>
</head>
<body>
<div class="wrep">
<div class="top">
<div class="tab ta">Tab1</div>
<div class="tab">Tab2</div>
<div class="tab">Tab3</div>
<div class="tab">Tab4</div>
<div class="tab">Tab5</div>
</div>
<div class="bottom">
<div class="tap">这是第1个页面</div>
<div class="tap">这是第2个页面</div>
<div class="tap">这是第3个页面</div>
<div class="tap">这是第4个页面</div>
<div class="tap">这是第5个页面</div>
</div>
</div>
</body>
</html>
对跳转页面进行隐藏
并且使第一个页面显示
.tap {
width: 400px;
height: 350px;
line-height: 350px;
background-color: rgb(0, 207, 17);
color: #fff;
text-align: center;
display: none;
}
.tap:first-of-type {
display: block;
}
接下来开始来开始写点击事件的部分:
首先获取top部分和bottom部分的class名
var tab = document.querySelectorAll(".tab");
var tap = document.querySelectorAll(".tap");
利用for循环遍历top的每个内容,然后给每个内容添加点击事件
for(let i=0;i<tab.length;i++){
tab[i].addEventListener("click", function(){}
}
在点击事件内添加top部分的css样式变换以及bottom部分的样式变换来达到点击切换的效果
for(let i=0;i<tab.length;i++){
tab[i].addEventListener("click", function(){
this.classList.add('ta');
tap[i].style.display = 'block';
}
})
}
最后使其他内容恢复原来的样式
我们用if语句做一个判断:
for(let i=0;i<tab.length;i++){
tab[i].addEventListener("click", function(){
this.classList.add('ta');
tap[i].style.display = 'block';
for(let j=0; j<tap.length; j++){
if(i !== j){
tab[j].classList.remove('ta');
tap[j].style.display = 'none';
}
}
})
}
以上就是利用js做的一个点击跳转页面的全部页面了。