简体   繁体   中英

Is there a straightforward way of detecting focus changes in a container element?

In the following code:

 div {padding: 10px; border: 1px solid black} div.whenFocused {background: yellow} input {display: block} * {outline: none} 
 <div tabindex=0> Text: <input> </div> 

Is there a simple way of detecting when the DIV gained or lost focus, either directly or indirectly through one of its children?

I need the DIV to have a yellow background whenever the user is interacting with it. The DIV is focusable so the user may arrive there via keyboard or mouse.
If they use the mouse, clicking anywhere inside the DIV must trigger a background-color change. Also, clicking outside the DIV must return the background-color to normal.

I already have this behavior implemented with a couple of helper functions and by listening to several events on different elements. But it's too much code for such a simple thing.

I'm sure there must be a simple and straightforward way, but I can't think of one right now.
(By simple I mean listening to a couple of events plus a couple of one-liner event-handlers and that's it)

I found a simple solution using jQuery:

$('div').on('focusin focusout',function(){ $(this)[(this.contains(document.activeElement)?'add':'remove')+'Class']('whenFocused') })

It's not exactly straightforward, but at least it's a one-liner.

It requires support for:
focusin / focusout
Node.contains
document.activeElement

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