利用事件委派與兄弟節點查找,極少代碼即可完成 Tab 切換:滑鼠移入標籤,隱藏所有內容區,顯示對應區塊,並切換標籤高亮類。
$(function() {
$('.tabs span').mouseover(function() {
$('.tabs div').hide(); // 隱藏所有內容
$(this).addClass('active') // 當前標籤高亮
.siblings('span').removeClass('active') // 兄弟標籤移除高亮
.end() // 回到當前 span
.next('div').show(); // 顯示緊鄰的內容 div
});
});
<div class="tabs">
<span class="active">熱點新聞</span><div id="tab-01">內容 1</div>
<span>娛樂新聞</span><div id="tab-02">內容 2</div>
<span>就業形勢</span><div id="tab-03">內容 3</div>
</div>
.tabs { position: relative; overflow: hidden; width: 360px; height: 160px; }
.tabs span { float: left; cursor: pointer; border: 1px solid #d5d5d5; width: 95px; line-height: 25px; text-align: center; margin-right: 5px; }
.tabs span.active { background: #d5d5d5; }
.tabs div { position: absolute; top: 26px; left: 0; width: 338px; height: 93px; padding: 10px; border: 1px solid #d5d5d5; display: none; }
#tab-01 { display: block; } /* 預設顯示第一個 */
$('.tabs span').click(function() {
var idx = $(this).index();
$(this).addClass('active').siblings().removeClass('active');
$('.tabs div').eq(idx).fadeIn().siblings('div').hide();
});