本文實(shí)例講述了JavaScript實(shí)現(xiàn)的伸展收縮型菜單代碼。分享給大家供大家參考。具體如下:
運(yùn)行效果截圖如下:
鼠標(biāo)懸浮時(shí)菜單項(xiàng)向上移動(dòng)成藍(lán)底白字,點(diǎn)擊之后底部會(huì)有藍(lán)條表示當(dāng)前選中項(xiàng)。
頁(yè)面代碼,菜單的每一項(xiàng)都是一個(gè) div ,其中包括一個(gè) ul 用來(lái)放置顯示文字等,另一個(gè) div 則是底部的藍(lán)條,需要給第一項(xiàng)和最后一項(xiàng)設(shè)置不同的 class ,樣式需要用到:
<div id="nav"> <div class="navItem indexNavItem"> <ul class="navUl"> <li>首頁(yè)</li> <li class="hoverLi">首頁(yè)</li> </ul> <div class="highlighter selectedNav"></div> </div> <div class="navItem"> <ul class="navUl"> <li>A</li> <li class="hoverLi">A</li> </ul> <div class="highlighter"></div> </div> <div class="navItem lastNavItem"> <ul class="navUl"> <li>A</li> <li class="hoverLi">A</li> </ul> <div class="highlighter"></div> </div> <div id="logoutNavItem" class="navItem logoutNavItem lastNavItem"> <ul class="navUl"> <li>退出</li> <li class="hoverLi">退出</li> </ul> <div class="highlighter"></div> </div> </div>
樣式,主要就是每個(gè)菜單項(xiàng)的左右邊框的設(shè)置以及 ul 和 li 的位置設(shè)置:
* { padding: 0; margin: 0; } body { background-color: #fffff3; font: 12px/1.6em Helvetica, Arial, sans-serif; } ul,li{ list-style: none; } #nav { text-align: center; height: 50px; font-size: 10px; line-height: 30px; background-color: #F0E6DB; margin-bottom: 10px; } .navItem { cursor: pointer; position: relative; float: left; width: 100px; height: 50px; font-size: 15px; border-right: 2px solid rgb(255,255,255); border-left: 2px solid rgb(255,255,255); overflow: hidden; font-weight:bold; } .indexNavItem { border-left: 4px solid rgb(255,255,255); margin-left: 10px; } .lastNavItem { border-right: 4px solid rgb(255,255,255); } .logoutNavItem { float: right; width: 120px; margin-right: 10px; border-left: 4px solid rgb(255,255,255); } .navUl { position: relative; height: 100px; width: 100%; border-bottom: 5px solid rgb(2,159,212); } .navUl li { height: 50px; line-height: 50px; } .highlighter { position: absolute; bottom: 0; height: 5px; width: 100%; } .selectedNav { background-color: #029FD4; } .hoverLi { background-color: #029FD4; color: #ffffff; }
接下來(lái)就是給菜單編寫懸浮和單擊事件的 js 代碼了,懸浮時(shí)將 ul 上移 li 的高度,鼠標(biāo)移開后再恢復(fù),點(diǎn)擊之后就是給藍(lán)條的 div 添加樣式即可:
$(function() { $(".navItem").hover(function() { $(this).children("ul").animate({ top: "-50px" }, 100); }, function() { $(this).children("ul").animate({ top: "0px" }, 100); }); $(".navItem").click(function(event) { $(this).siblings().children('.highlighter').removeClass('selectedNav'); $(this).children('.highlighter').addClass('selectedNav'); }); })
以上就是jQuery實(shí)現(xiàn)簡(jiǎn)潔的導(dǎo)航菜單效果的關(guān)鍵代碼,希望對(duì)大家的學(xué)習(xí)有所幫助。