今日天氣
晴
晴
我認(rèn)為掌握tab欄切換算是從靜態(tài)頁面到動態(tài)頁面所邁出的第一步互艾,并且在以后的工作中會作為js基礎(chǔ)中的基礎(chǔ),反復(fù)的使用讯泣,所以掌握tab欄切換至關(guān)重要H移铡!好渠!
- 入門級tab欄切換
html
<ul>
<p class="current" onclick="change(0)">web前端</p>
<p class="" onclick="change(1)">java語言</p>
<p class="" onclick="change(2)">c++語言</p>
</ul>
<hr>
<div class="bg1 item">111</div>
<div class="bg2 item">222</div>
<div class="bg3 item">333</div>
css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
li{
list-style: none;
}
.current{
background-color: blue;
color: white;
}
ul{
display: flex;
width: 300px;
}
ul p{
display: flex;
justify-content: center;
align-items: center;
border: 1px solid;
width: 100px;
height: 30px;
cursor: pointer;
}
.bg1{
width: 300px;
height: 300px;
border: 1px solid;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.bg2{
width: 300px;
height: 300px;
border: 1px solid;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
display: none;
}
.bg3{
width: 300px;
height: 300px;
border: 1px solid;
background-color: green;
display: flex;
justify-content: center;
align-items: center;
display: none;
}
js
function change(num) {
var tab = document.querySelector('ul').querySelectorAll('p');
var _item = document.querySelectorAll('.item');
for(var i = 0;i<tab.length;i++){
tab[i].className = '';
}
tab[num].className = 'current';
for(var i = 0;i<tab.length;i++){
_item[i].style.display = 'none';
}
_item[num].style.display = 'flex';
}
- Q1. tab[i].className = ' ';是什么意思局嘁?
答:通過for循環(huán)遍歷所有的i,從0開始直到tab的長度(tab就是定義的一個偽數(shù)組,長度就是里面p標(biāo)簽的個數(shù))晦墙,例如tab獲取到的是ul標(biāo)簽下的所有p標(biāo)簽悦昵,,tab.length就是3晌畅。tab[i]就是所有的三個p標(biāo)簽但指,然后tab[i].className = ' ';意思就是所有的p標(biāo)簽的class屬性設(shè)為空(也就是取消css樣式)。 -
Q2. tab[num].className = 'current';是什么意思抗楔?
答:tab[num].className = 'current';意思是將類名為“current”的樣式應(yīng)用到當(dāng)前的p標(biāo)簽(tab綁定了p標(biāo)簽)棋凳。