萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 彈出下拉菜單特效完整實現(含 CSS 樣式)

效果預覽

鼠標懸停主導航項,彈出二級下拉菜單,帶背景高亮與圓角按鈕樣式。

HTML 結構

<ul class="nav_tukankan">
    <li><a href="#" class="one">菜單一</a>
        <ul class="two">
            <li><a href="#">子項 1</a></li>
            <li><a href="#">子項 2</a></li>
        </ul>
    </li>
    <li><a href="#" class="one">菜單二</a>
        <ul class="two">
            <li><a href="#">子項 3</a></li>
            <li><a href="#">子項 4</a></li>
        </ul>
    </li>
</ul>

核心 CSS(精簡版)

.nav_tukankan { 
    border-bottom: 1px solid #ccc; 
    height: 62px; 
    line-height: 62px; 
    background: #fff; 
}
.nav_tukankan li { 
    float: left; 
    width: 131px; 
    position: relative; 
}
.nav_tukankan .one { 
    display: block; 
    width: 93px; 
    height: 62px; 
    color: #000; 
    text-decoration: none; 
}
.nav_tukankan .one:hover,
.nav_tukankan .onethis { 
    background: #2c2f36; 
    color: #fff; 
    font-weight: bold; 
}
.nav_tukankan .two { 
    display: none; 
    position: absolute; 
    top: 62px; 
    left: 0; 
    width: 320px; 
    padding: 8px; 
    background: #2c2f36; 
    color: #fff; 
    z-index: 9999; 
}
.nav_tukankan .two li { 
    width: 80px; 
    height: 28px; 
    line-height: 28px; 
    float: left; 
    text-align: center; 
}
.nav_tukankan .two a { 
    display: block; 
    width: 80px; 
    height: 25px; 
    border-radius: 3px; 
    color: #fff; 
}
.nav_tukankan .two a:hover { 
    text-decoration: underline; 
}

jQuery 交互邏輯

$(function() {
    $(".nav_tukankan > li").hover(
        function() {
            $(this).find(".two").stop(true, true).slideDown(200);
            $(this).find(".one").addClass("onethis");
        },
        function() {
            $(this).find(".two").stop(true, true).slideUp(200);
            $(this).find(".one").removeClass("onethis");
        }
    );
});

關鍵點

  • 父 li 設置 position: relative,子菜單 absolute 定位
  • z-index: 9999 確保下拉層疊加頂層
  • stop(true, true) 防止快速懸停導致動畫隊列堆疊
  • 純 CSS 也可實現(:hover),JS 增強動畫體驗
copyright © 萬盛學電腦網 all rights reserved