如何使用JavaScript/jQuery点击选项时关闭下拉列表?
解决点击下拉列表选项后关闭列表的问题
问题说明
当前通过CSS的hover事件控制下拉列表显示,鼠标移开时列表正常消失,但点击选项时无法关闭列表。使用Bootstrap 4,可点击元素为DIV或表格单元格,点击事件能正常触发,但尝试的几种JS方法均未达到预期效果。
解决方案
方法一:精准控制下拉列表的显示状态
把点击事件绑定到下拉选项上,定位当前所属的下拉列表进行隐藏,同时修复hover的触发逻辑:
// 绑定选项点击事件 $('.custom-dropdown .dropdown-menu li').on('click', function(e) { console.log("You selected: " + e.target.innerText); // 隐藏当前点击项所属的下拉列表 $(this).closest('.dropdown-menu').css('display', 'none'); // 阻止事件冒泡,避免干扰父元素的hover状态 e.stopPropagation(); }); // 确保hover能重新触发显示 $('.custom-dropdown').hover(function() { $(this).find('.dropdown-menu').css('display', 'block'); }, function() { $(this).find('.dropdown-menu').css('display', 'none'); });
方法二:通过临时类覆盖hover样式
添加一个CSS类来强制隐藏列表,鼠标离开父元素后移除该类,不影响后续hover:
新增CSS
.custom-dropdown .dropdown-menu.hidden { display: none !important; }
修改JS
$('.custom-dropdown .dropdown-menu li').on('click', function(e) { console.log("You selected: " + e.target.innerText); const dropdownMenu = $(this).closest('.dropdown-menu'); // 添加类隐藏列表 dropdownMenu.addClass('hidden'); e.stopPropagation(); // 鼠标离开父元素时移除类,恢复hover功能 dropdownMenu.closest('.custom-dropdown').one('mouseleave', function() { dropdownMenu.removeClass('hidden'); }); });
完整示例代码
HTML
<table class="table table-bordered"> <tbody> <tr> <td class="text-center dropdown custom-dropdown" style="background-color: red">JavaScript <ul class="dropdown-menu custom-dropdown-list mt-0"> <li class="text-center" style="background-color: lightgreen;">HTML</li> <li class="text-center" style="background-color: yellow;">CSS</li> <li class="text-center" style="background-color: lightblue;">C#</li> </ul> </td> </tr> </tbody> </table> <div style="background-color: red" class="text-center dropdown custom-dropdown"> JavaScript <ul class="dropdown-menu custom-dropdown-list mt-0"> <li class="text-center" style="background-color: lightgreen;">HTML</li> <li class="text-center" style="background-color: yellow;">CSS</li> <li class="text-center" style="background-color: lightblue;">C#</li> </ul> </div>
CSS(包含hover和临时类样式)
.custom-dropdown:hover .dropdown-menu { display: block; } .custom-dropdown .dropdown-menu.hidden { display: none !important; }
JS(使用方法二的代码)
$('.custom-dropdown .dropdown-menu li').on('click', function(e) { console.log("You selected: " + e.target.innerText); const dropdownMenu = $(this).closest('.dropdown-menu'); dropdownMenu.addClass('hidden'); e.stopPropagation(); dropdownMenu.closest('.custom-dropdown').one('mouseleave', function() { dropdownMenu.removeClass('hidden'); }); });
内容的提问来源于stack exchange,提问作者Cass
相关产品推荐
相关产品推荐

