简体   繁体   中英

Focus and blur events for HTMLDivElement?

I implemented a custom drop down with HTML, CSS and 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. The event basically checks whether the DOM event happened on the right element using target and if not, then blur the drop down control.

I know about focus and blur . 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.

What I do is use mouseout to close my custom lists. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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