有没有办法确定一个 <select>下拉菜单是否打开?

人气:878 发布:2022-10-16 标签: javascript popup drop-down-menu dom menu

问题描述

我正在寻找一种方法来确定 <select> 元素的菜单是否/何时打开.我不需要强制它打开或关闭,只需确定它在给定时间是打开还是关闭.

I'm looking for a way to determine if/when a <select> element's menu is open. I don't need to force it to open or close, just figure out if it's open or closed at a given time.

我可以监听焦点/模糊、mouseup/mousedown 等事件,但我认为我不能可靠地从这些事件中找出菜单的状态.例如,mousedown 后跟 mouseup 可能意味着用户单击并拖动到选择并释放(在这种情况下菜单现在关闭)或单击并释放以打开菜单(在这种情况下菜单打开).下拉菜单的特定行为似乎也取决于浏览器.

I can listen to events for focus/blur, mouseup/mousedown, etc., but I don't think I can reliably figure out the state of the menu from those events. For example, mousedown followed by mouseup could mean the user clicked and dragged to a selection and released (in which case the menu is now closed) or clicked and released to open the menu (in which case the menu is open). It also seems likely that the specific behavior of dropdown menus is browser-dependent.

如果我滚动自己的下拉菜单,我知道我可以做到这一点,但我更喜欢使用 <select>.

I know I could do this if I roll my own dropdown menu, but I prefer to use <select>.

是否有可靠的方法来确定下拉菜单是否打开?还是这是 Javascript 无法知道的?

Is there a reliable way to find out if a dropdown menu is open? Or is this something that Javascript can't know?

结论:似乎没有任何保证方法可以确定选择菜单是否打开,无论是通过询问对象还是通过侦听它触发的事件.

Conclusion: There doesn't seem to be any guaranteed way to determine if a select menu is open, either by asking the object or by listening to the events it fires.

为了我自己的使用,我只是使用 onfocus 和 onblur 来跟踪选择是否具有焦点.我假设没有焦点就无法打开菜单,这在我测试过的所有浏览器中似乎都是正确的.它实际上并没有告诉我菜单何时打开,但它会告诉我它何时无法打开,这对我的目的来说已经足够了.

For my own use I'm just keeping track of whether the select has focus using onfocus and onblur. I'm assuming there's no way for the menu to be open without having focus, and that seems to hold true in all the browsers I've tested. It doesn't actually tell me when the menu is open, but it tells me when it can't be open, which is good enough for my purposes.

推荐答案

您可以在 select 的 option 子元素中使用 mouseenter 事件,因为您只能在其中输入选择菜单已打开,或者也与 select 元素上的 click 事件一起打开,通常在您打开它时引发.

You can play with mouseenter event in select's option child elements as you can only enter in them if select menu is open, or also with the click event on the select element, usually thrown when you open it.

在精确的时刻测试它是否打开我认为是不可能的.

To test in a precise moment if its open or not I think is not possible.

344