使用jq寫選項卡,告別了繁瑣的循環以及命名規範
基本原理:
1.當某一個btn被選中時,將這個btn的背景顏色設為橘色,其餘兄弟btn背景顏色設為空(none)
2.如果子div與btn的索引相同,就將這個div顯示而其他兄弟div隱藏
1).css函數參數2的回調函數方法;
2).原生get方法再轉jq對象 再進行設置的方法
3).當前div使用show()方法,其餘兄弟div使用hide()方法
關鍵字:get() siblings() show() hide() css()
html頁:
4個btn,4個div
<div id=”wrap”>
<button>btn1</button>
<button>btn2</button>
<button>btn3</button>
<button>btn4</button>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
css頁:
大盒子當前無樣式,在實際開發中需要指定其寬高;第一個btn背景色為橘黃色;第一個子項div顯示,其餘兄弟div隱藏
#wrap div {
width: 300px;
height: 200px;
border: 1px solid red;
display: none;
}
#wrap div:nth-of-type(1) {
display: block;
/* 第一個子項div顯示 */
}
#wrap button:nth-of-type(1) {
background: orange;
/* 第一個btn背景色為橘黃色; */
}
jquery頁:
1)首先給btn綁定事件
$(“#wrap button”).click(function() {
//當btn被點擊後發生的事件
})
關鍵字: click();
2) 當btn被點擊時,設置當前選中btn顏色為橘色,並且將其他兄弟btn背景色為空:
$(this).css(“background”, “orange”).siblings(“button”).css(“background”, “none”)
關鍵字: $(this); css(); siblings()
3) 聲明一個變數,這個變數保存了被選中的btn的下標
var $index = $(this).index();
關鍵字:$index; $(this);index();
// 1:找到所有的子div,並且設置css樣式,如果某個div的索引與btn的索引相同,就讓他顯示
$(“#wrap div”).css(“display”, function(i) {
if (i == $index) {
return “block”;
}
return “none”;
})
關鍵字:css() ; “display” ; i == $index;
b:通過get()方法將子div的索引與當前btn的索引綁定,然後再將這個索引轉變成jq對象,再使用jq方法將對應div顯示
1
$($(“#wrap div”).get($(this).index())).css(“display”, “block”).siblings(“div”).css(“display”, “none”)
由於get方法是js原生方法,所以應將其轉成jq對象才能使用jq方法
關鍵字: $() ; $(this).index; get();css();siblings()
c:通過當前btn的索引綁定div的索引,進而將這個索引對應的div顯示show(),並將其餘的div兄弟元素隱藏hide()
$(“#wrap div”).eq($(this).index()).show().siblings(“div”).hide();
關鍵字:eq();$(this).index();show();hide()
這樣,就完成了使用jQuery方法實現選項卡。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/274725.html
微信掃一掃
支付寶掃一掃