jQuery下拉框聚焦失效及点击触发下拉菜单的实现求助
Hey there! Let's break down and solve your two jQuery issues step by step:
First off, if your dropdown trigger (like that .dropdown-btn div) isn't responding to focus events, it's probably because block elements like <div> aren't natively focusable by default. Browsers only consider elements like inputs, buttons, or elements with a tabindex attribute as focusable.
Fix steps:
- Add a
tabindexattribute to your dropdown button so it can receive focus:
<div class="dropdown-btn" tabindex="0">Go To...</div>
- Then bind the
focusandblurevents in jQuery to control the dropdown:
// Show dropdown on focus $('.dropdown-btn').on('focus', function() { $(this).next('.navbar-tab').show(); }); // Hide dropdown when focus is lost $('.dropdown-btn').on('blur', function() { $(this).next('.navbar-tab').hide(); });
This makes the div act like a focusable element, so your jQuery focus logic will kick in as expected.
ul li展开对应下拉菜单的交互 You mentioned wanting a behavior similar to ul li:hover ul but triggered by click (like a focus-based logic). Let's assume your HTML has submenus nested under the .navbar-tab-1 items (since you referenced "Searches..." as a dropdown). Here's how to make this work with jQuery:
First, set up basic CSS to hide submenus by default:
.navbar-tab .submenu { display: none; }
(Replace .submenu with your actual submenu class if it's different)
Then the jQuery logic:
// Toggle submenu when clicking a parent list item $('.navbar-tab-1').on('click', function(e) { // Stop the click from bubbling up to parent elements e.stopPropagation(); // Toggle the current item's submenu const $submenu = $(this).find('.submenu'); $submenu.toggle(); // Close all other submenus to keep things clean $('.navbar-tab-1').not(this).find('.submenu').hide(); }); // Close all submenus when clicking anywhere else on the page $(document).on('click', function() { $('.navbar-tab .submenu').hide(); });
How this works:
- Clicking a
.navbar-tab-1item will toggle its submenu open/closed. - It automatically closes other open submenus so only one is visible at a time.
- Clicking anywhere outside the menu closes all submenus, mimicking a "focus out" behavior.
If you specifically wanted to use focus instead of click, you could add tabindex="0" to each .navbar-tab-1 item and swap the click event for focus/blur—but click is usually more intuitive for dropdown menus triggered by user interaction.
内容的提问来源于stack exchange,提问作者Sang Nguyen

