首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

jQuery 實現鼠標懸停顯示、點擊空白區域隱藏的下拉層交互

     編輯:程式設計綜合問答

需求描述

  • 鼠標懸停 li 顯示其內部 div 隱藏層。
  • 鼠標移出 li 隱藏該層。
  • 點擊頁面空白區域隱藏所有層。
  • 懸停新 li 時自動隱藏其他層。

完整 jQuery 實現

<style>
.dropdown-layer { display: none; position: absolute; z-index: 100; }
</style>

<ul class="menu">
    <li>Item 1 <div class="dropdown-layer">Layer 1</div></li>
    <li>Item 2 <div class="dropdown-layer">Layer 2</div></li>
    <li>Item 3 <div class="dropdown-layer">Layer 3</div></li>
</ul>

<script>
$(function() {
    var $layers = $('.dropdown-layer');
    var $menuItems = $('.menu > li');

    // 1. 懸停顯示/隱藏
    $menuItems.hover(
        function() {           // mouseenter
            $layers.hide();    // 隱藏所有其他層
            $(this).find('.dropdown-layer').show();
        },
        function() {           // mouseleave
            $(this).find('.dropdown-layer').hide();
        }
    );

    // 2. 點擊空白區域隱藏所有
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.menu').length) {
            $layers.hide();
        }
    });

    // 3. 防止菜單內部點擊冒泡觸發文檔隱藏
    $menuItems.on('click', function(e) {
        e.stopPropagation();
    });
});
</script>

CSS 純樣式替代方案 (無 JS)

.menu > li {
    position: relative;
}
.menu > li .dropdown-layer {
    display: none;
    position: absolute;
    left: 100%; top: 0;
}
.menu > li:hover .dropdown-layer {
    display: block;
}

/* 點擊外部關閉需配合 :focus-within 或 checkbox hack,純 CSS 難以完美實現 */

純 CSS 適合簡單懸停菜單,但「點擊空白關閉」通常需要 JS 輔助。

關鍵 API 對照

jQuery 方法作用
.hover(enterFn, leaveFn)綁定 mouseenter/mouseleave,自動處理子元素冒泡
.closest(selector)向上查找最近匹配祖先元素
e.stopPropagation()阻止事件向文檔冒泡
.hide() / .show()切換 display:none/block

性能優化提示

  • 將 $layers、$menuItems 緩存為變量,避免重複選擇器查詢。
  • 事件委託 $(document).on('click', ...) 單一監聽器處理動態添加的菜單。
  • 大量菜單項時考慮 requestAnimationFrame 批量隱藏/顯示。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved