JavaScript中选项卡的几种写法
效果图:
1.基本写法
<!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>
ul li{
list-style: none;
}
ul{
width: 300px;
height: 40px;
background: #ccc;
display: flex;
justify-content: space-between;
padding: 0;
margin: 0;
}
li{
width: 33%;
text-align: center;
line-height: 40px;
}
li.active{
background: red;
}
.box{
width: 298px;
height: 200px;
border: 1px solid red;
}
.box p {
height: 200px;
display: none;
margin: 0;
}
.box p.active{
display: block;
}
.box p:nth-child(1){
background: yellowgreen;
}
.box p:nth-child(2){
background: indianred;
}
.box p:nth-child(3){
background:mediumturquoise;
}
</style>
</head>
<body>
<div>
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="box">
<p class="active">1111111111111111111111111111111</p>
<p>2222222222222222222222222222222</p>
<p>3333333333333333333333333333333</p>
</div>
</div>
</body>
<script>
var ol=document.querySelectorAll("li");
var op=document.querySelectorAll("p");
for(var i=0;i<ol.length;i++){
ol[i].index=i;
ol[i].onclick=function(){
for(var j=0;j<ol.length;j++){
ol[j].className="";
op[j].style.display="none";
}
this.className="active";
op[this.index].style.display="block"
}
}
</script>
</html>
|
2.面向对象
<!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>
ul li{
list-style: none;
}
ul{
width: 300px;
height: 40px;
background: #ccc;
display: flex;
justify-content: space-between;
padding: 0;
margin: 0;
}
li{
width: 33%;
text-align: center;
line-height: 40px;
}
li.active{
background: red;
}
.box{
width: 298px;
height: 200px;
border: 1px solid red;
}
.box p {
height: 200px;
display: none;
margin: 0;
}
.box p.active{
display: block;
}
.box p:nth-child(1){
background: yellowgreen;
}
.box p:nth-child(2){
background: indianred;
}
.box p:nth-child(3){
background:mediumturquoise;
}
</style>
</head>
<body>
<div>
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="box">
<p class="active">1111111111111111111111111111111</p>
<p>2222222222222222222222222222222</p>
<p>3333333333333333333333333333333</p>
</div>
</div>
</body>
<script>
//选项卡:点击对应按钮的时候,切换对应的内容
// 1.选元素
// 2.绑定事件
// 3.找点击的元素的索引
// 4.根据索引,显示内容
function Tab(){
this.li=document.querySelectorAll("li");
this.p=document.querySelectorAll("p");
this.init();
}
Tab.prototype.init=function(){
var that=this;
for(var i=0;i<this.li.length;i++){
this.li[i].index=i;
this.li[i].onclick=function(){
that.abc=this.index;
that.display();
}
}
}
Tab.prototype.display=function(){
for(var i=0;i<this.li.length;i++){
this.li[i].className="";
this.p[i].className="";
}
this.li[this.abc].className="active";
this.p[this.abc].className="active";
}
new Tab();
</script>
</html>
|