检测第一次单击时选择元素 onBlur 的单击关闭。 (默认为第二次点击)
我已经阅读了有关检测选择菜单状态的问题,无论它是 可见, 打开,或 < a href="https://stackoverflow.com/questions/6207929/is-there-a-dom-event-that-fires-when-an-html-select-element-is-close">已关闭快速的答案是它不是通用的,取决于您想要做什么。这些答案都不能 100% 涵盖我的情况。
我需要确定选择菜单何时关闭,当前通过存储变量 onblur 来工作;但是,选择元素不会在第一次单击时失去焦点,而是在第二次单击时失去焦点。是否有我可以检测到第一次点击关闭时发生的事件?或者使选择在第一次单击关闭而不是第二次单击关闭时失去焦点?寻找纯 JavaScript 答案,而不是 jQuery。
下面是一些示例代码,演示了这一点: http://jsfiddle.net/BhnH9/1/
I've read up on questions pertaining to detecting the state of a select menu, whether it's visible, open, or closed and the quick answer is that it's not universal and depends on what you're trying to do. My situation isn't covered by any of these answers 100%.
I need to determine when the select menu is closed, which currently works by storing a variable onblur
; however, the select element does not lose focus on the first click off, but rather the second click off. Is there an event I can detect which occurs on the first click off? or make the select lose focus on the first click off rather than the second click off? Looking for pure JavaScript answers, no jQuery.
Here's some sample code demonstrating this: http://jsfiddle.net/BhnH9/1/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在文档(或选择的其他合适的祖先)上使用常规单击侦听器,并查看选择元素是否与 document.activeElement。如果是这样,那么它就具有焦点,因为它刚刚获得焦点或者已经选择了一个选项。
但是,除了单击之外,还有其他选择选项的方法,例如键盘导航。点击侦听器不会为您提供帮助。
You can use a general click listener on the document (or some other suitable ancestor of the select) and see if the select element matches the document.activeElement. If so, then it has focus either because it just got it or an option has been selected.
However, there are other ways of selecting options than clicks, such as keyboard navigation. A click listener will not help you there.
最近这个帖子有评论,所以我决定再看看这个问题。我不太记得原来的情况是什么,但我确实知道我需要选择下拉菜单才能在选择一个项目后失去焦点。所以你瞧,我的 jQuery 解决方案...我说它一定不是 jQuery :) 已经很长一段时间了,我换了工作,但不知道为什么这是一个要求。
这是一个 JSFiddle: http://jsfiddle.net/7tUse/
Recently there was a comment on this thread, so I decided to take another look at the issue. I don't recall quite what the original circumstances were, but I do know that I needed the select drop down to lose focus after selected an item. So lo and behold, my jQuery solution... what with me saying it had to not be jQuery :) It's been a long time, I've switched jobs, and don't know why that was a requirement.
Here's a JSFiddle: http://jsfiddle.net/7tUse/