简体   繁体   English

聚焦和模糊HTMLDivElement的事件?

[英]Focus and blur events for HTMLDivElement?

I implemented a custom drop down with HTML, CSS and JavaScript. 我使用HTML,CSS和JavaScript实现了自定义下拉菜单。 It works well now, but I am not happy with the way I am doing "blurring" right now. 现在效果很好,但是我对现在进行“模糊处理”的方式不满意。 When you open the list, and then click somewhere else, it should collapse. 当您打开列表,然后单击其他位置时,它应该折叠。 What I did was that I added an event listener ( mousedown ) to the window after expanding the list, and removing the listener after collapsing. 我所做的是,在扩展列表之后,在window添加了事件侦听器( mousedown ),并在折叠后删除了该侦听器。 The event basically checks whether the DOM event happened on the right element using target and if not, then blur the drop down control. 该事件基本上使用target检查DOM事件是否发生在正确的元素上,如果不是,则模糊下拉控件。

I know about focus and blur . 我知道focusblur However, they only seem to work on form elements, which I find quite understandable. 但是,它们似乎只适用于表单元素,我认为这是可以理解的。 They also support other scenarios like when "tabbing" away. 它们还支持其他情况,例如“跳开”时。

Anyway, I am asking you if there is a better way of doing what I am doing right now. 无论如何,我问你现在是否有更好的方法来做我正在做的事情。 What I do just feels stupid. 我所做的只是觉得愚蠢。

Maybe you could have a dummy input and focus that when the control is active. 也许您可以有一个虚拟输入,并在控件处于活动状态时集中精力。 Then watch the blur and close the list. 然后观看模糊并关闭列表。 It would not be able to be display:none but maybe opacity:0 , or just out-of-view. 它将无法display:none但可能opacity:0 ,或者仅在视线之外。

What I do is use mouseout to close my custom lists. 我要做的是使用mouseout关闭我的自定义列表。 I create a bounding box around my drop down. 我围绕下拉菜单创建一个边界框。 That box has the onmouseout event attached to it that closes the drop down when the mouse moves outside of it. 该框具有附加的onmouseout事件,当鼠标移出该框时,该事件会关闭下拉菜单。 This way you can have a little padding outside your list that would give your users a little better functionality then just mouseout on your basic list. 这样,您可以在列表之外添加一些填充,这将为用户提供更好的功能,而后只需将鼠标移出基本列表即可。

If you want to do it using click events, I would have a global function, like it seems you have setup, and call that function on any click events on the page. 如果您想使用单击事件来执行此操作,那么我将拥有一个全局函数,就像您已经设置了该函数一样,并在页面上的所有单击事件上调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM