简体   繁体   中英

Working with focus and blur events on DOM nodes

I have an input type=text control T that when focused runs some JavaScript to show a div UI element E .

When T is blurred, E is hidden by an onblur callback.

But when the user clicks on E , T is of course blurred, but in this case I do not want to hide E .

How can I distinguish in the onblur callback for T between a normal blurring and a blurring to somewhere within the control?

I have tried document.activeElement , but this returns the body element which is of no use to me.

Minimum example:

https://jsfiddle.net/1w8hr5jr/

Edit:

Is it the case that because only certain kinds of DOM node can receive focus, that focus and blur are insufficiently powerful for my needs here?

My suggestion, as said in my comment, is to use a click event instead of blur and focus

html

<div id="container">
  <input type="text" id="foo"></input>
  <div id="bar">
    hello
  </div>
</div>

javascript

var container = document.getElementById('container');
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');

function onFocus() {
  bar.style.display = 'block';
}

function onClick(evt) {
  if (evt.target === foo) {
     bar.style.display = 'block';
  } else if (evt.target !== bar) {
     bar.style.display = 'none';
  }
}

container.addEventListener('click', onClick);

https://jsfiddle.net/she5fqmh/2/

I had the same challenge lately, and this is the best workaround I have found

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