1. 程式人生 > >Tab選項卡切換效果

Tab選項卡切換效果

tab選項卡是網頁中最常見的切換效果,常見的tab切換型別有:滑鼠滑過切換、點選切換、延遲切換、以及自動切換。


html結構:

<div class="notice"> <div class="notice-tit" id="notice-tit"> <ul> <li class="selected">公告</li> <li>規則</li> <li>論壇</li> <
li>安全</li> <li>教育</li> </ul> </div> <div class="notice-con" id="notice-con"> <div style="display:block">test1</div> <div>test2</div> <div>test3</div> <
div>test4 </div> <div>test5 </div> </div> </div>

css樣式:

.notice { width: 298px; border: 1px solid #ddd; /* 盒子的總寬度w=298+1+1=300px */ height: 98px; overflow: hidden; /* 點選導航欄第一個或最後一個標籤時,超出的部分隱藏*/
margin: 10px; } .notice-tit { position: relative; height: 28px; } .notice-tit ul { position: absolute; width: 301px; left: -1px; /* 當點選第一個導航欄標籤時,左邊邊框會與大盒子的邊框發生疊加,解決的方法利用定位讓兩個邊框重合疊加在一起 */ height: 27px; background: #f7f7f7; border-bottom: 1px solid #ddd; } .notice-tit ul li { float: left; width: 58px; padding: 0 1px; height: 27px; text-align: center; line-height: 27px; cursor: pointer; } .notice-tit ul li.selected { border-left: 1px solid #ddd; border-right: 1px solid #ddd; background: #fff; padding: 0; border-bottom: 1px solid #fff; } .notice-con div { height: 90px; padding: 20px; display: none; }

js方式實現tab選項卡:

<script> // 獲取滑鼠滑過或點選和需要展現的元素 var notice_tit = document.getElementById("notice-tit"), notice_con = document.getElementById("notice-con"), lis = notice_tit.getElementsByTagName('li'), divs = notice_con.getElementsByTagName('div'); for (var i = 0; i < lis.length; i++) { lis[i].id = i; lis[i].onclick = function() { for (var j = 0; j < lis.length; j++) { lis[j].className = ''; divs[j].style.display = 'none'; } this.className = 'selected'; divs[this.id].style.display = 'block'; } } </script>

jquery方法實現:

$('#notice-tit li').click(function() { $(this).siblings().removeClass('selected'); $(this).addClass('selected'); var index = $(this).index(); // 獲取當前點選元素的下標 // alert(index); $('#notice-con div').hide(); $('#notice-con div').eq(index).show(); })