萬盛學電腦網

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

jQuery 實現帶動畫的二級下拉導航選單

經典的二級下拉選單:滑鼠移入主選單項,子選單以 slideDown 動畫展開並淡入;移出則反向收合。同時主選單背景色與文字色同步動畫切換,子選單項目另有懸停變色效果。需引入 jQuery UI Core(含 Color Animations)以支援顏色動畫。

HTML 結構

<ul class="nav_list">
  <li>
    <a href="#" class="current">Test_1</a>
    <div class="second">
      <a href="#">menu_1</a> <a href="#">menu_1</a> <a href="#">menu_1</a>
    </div>
  </li>
  <li><a href="#">Test_2</a>
    <div class="second">...</div>
  </li>
  ...
</ul>

CSS 關鍵點

.nav_list li { float:left; position:relative; margin-right:10px; }
.nav_list li a { width:80px; display:block; padding:4px 0; background:#996666; color:#ccc; text-align:center; }
.nav_list li a.current { background:#f00; color:#fff; }
.nav_list li div.second {
    position:absolute; left:0; top:22px; width:80px; height:0; overflow:hidden; color:#999;
}
.nav_list li div.second a { display:block; width:80px; padding:5px 0; background:#666; color:#fff; border-top:1px solid #fff; }

jQuery 邏輯

$(function(){ Menu(".nav_list"); });

function Menu(ul_class_name) {
    Second(ul_class_name);
    var li_name = ul_class_name + " li";
    $("div.second").css("opacity", "0.1");

    $(li_name).hover(
        function() { // mouseenter
            var a_height = $(this).children("div.second a:first").css("height");
            var a_count = $(this).children("div.second").children("a").length;
            var slide_hieght = (parseInt(a_height) + 11) * a_count; // 含 padding/border
            $(this).children("div.second").stop().animate({height: slide_hieght + "px", opacity: "0.9"}, 600);
            $(this).children("a:not(.current)").stop().animate({backgroundColor: "#f00", color: "#fff"}, 800);
        },
        function() { // mouseleave
            $(this).children("div.second").stop().animate({height: "0px", opacity: "0.1"}, 600);
            $(this).children("a:not(.current)").stop().animate({backgroundColor: "#996666", color: "#ccc"}, 800);
        }
    );
}

function Second(ul_class_name) {
    var second_menu = ul_class_name + " li div.second > a";
    $(second_menu).hover(
        function() { $(this).stop().animate({backgroundColor: "#000", opacity: "1"}, 400); },
        function() { $(this).stop().animate({backgroundColor: "#666", opacity: "0.9"}, 400); }
    );
}

注意事項

  • 需引入 jquery.effects.core.min.js(jQuery UI 核心效果模組)才能讓 animate({backgroundColor...}) 生效。
  • 使用 .stop() 防止快速進出導致動畫佇列堆疊。
  • 現代 CSS 可用 transition 替代 JS 動畫,效能更好且無需額外庫。

純 CSS 替代方案

.nav_list li div.second { max-height:0; opacity:0; transition: max-height 0.4s, opacity 0.4s; }
.nav_list li:hover div.second { max-height:500px; opacity:0.9; }
.nav_list li a:not(.current) { transition: background-color 0.5s, color 0.5s; }
.nav_list li:hover a:not(.current) { background:#f00; color:#fff; }
copyright © 萬盛學電腦網 all rights reserved