HTML和CSS代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
list-style: none;
margin: 0;
padding: 0;
outline:0;
}
.sel{
width:300px;
height:300px;
border:1px solid #000;
margin: 0 auto;
margin-top: 100px;
}
.btn{
font-size: 0;
}
.btn button{
border:none;
width:33.33%;
height:50px;
cursor:pointer;
}
.btn button:hover{
background: yellow;
}
.content li{
margin-top: 50px;
width:100%;
height:150px;
display: none;
text-align: center;
cursor:default;
}
.content li:first-of-type{
display: block;
}
</style>
</head>
<body>
<div class="sel">
<div class="btn">
<button>html</button>
<button>css</button>
<button>javascript</button>
</div>
<ul class="content">
<li>HTML是超文本标记语言</li>
<li>CSS是层叠样式表</li>
<li>javascript是弱类型解释型动态脚本语言</li>
</ul>
</div>
</body>
</html>
方法1(this)
var btns = document.querySelectorAll(".btn button");
var ali = document.querySelectorAll('.content li');
for(var i=0;i<btns.length;i++){
btns[i].index = i;//自定义按钮属性index,将下标值储存起来
btns[i].addEventListener('click',function(){
for(var j=0;j<ali.length;j++){
ali[j].style.display='none';
}
ali[this.index].style.display = 'block';//this指向btns,即btns中index属性的下标值
})
}
方法2(闭包)
for(var i=0;i<btns.length;i++){
//立即执行函数
(function(k){ //k形参
//嵌套函数
btns[k].addEventListener('mouseenter',function(){
for(var j=0;j<ali.length;j++){
ali[j].style.display='none';
}
ali[k].style.display = "block";
})
})(i) //i实参
}
方法3(let)
- 与this类似,只是for循环中的i用let声明,通过let声明的块级变量,可将i值一个一个传进ali[i]
var btns = document.querySelectorAll(".btn button");
var ali = document.querySelectorAll('.content li');
for(let i=0;i<btns.length;i++){
btns[i].addEventListener('click',function(){
for(var j=0;j<ali.length;j++){
ali[j].style.display='none';
}
ali[i].style.display = 'block';
})
}
方法4(jQuery)
$(".btn button").on('click',function(){
$(".content li").eq($(this).index()).show().siblings().slideUp();
})
方法5(vue.js)
- HTML和CSS结构与上面不同
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
list-style:none;
}
.tab{
width:400px;
height:400px;
border:1px solid green;
margin: 0 auto;
}
.btn{
display: flex;
}
button{
width:33.33%;
height:60px;
}
.content{
text-align: center;
font-size: 30px;
}
[v-cloak]:{
display:none;
}
.active{
color:white;
background: #666;
}
</style>
</head>
<body>
<div class="tab" v-cloak>
<div class="btn">
<button v-for="(val,index) in btnText" v-on:click="selTab(index)" :class="{active:index==idx}" >{{val}}</button>
</div>
<ul class="content">
{{content[idx]}}
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el:".tab",
data:{
red:'red',
skyblue:'skyblue',
pink:'pink',
btnText:['html','css','javascript'],
content:['html是...',"css是...",'javascript是...'],
idx:0,//通过改变idx来显示隐藏对应的数据
isActive:true
},
methods:{
selTab(index){
this.idx = index;
}
}
})
</script>
</body>
</html>
网友评论