简体   繁体   中英

Safari doesn't correctly change active element on focus

I have a tooltip which depends on becoming the active element when clicked, so that on blur it can hide.

In a decent browser like Chrome a <button> becomes the active element when clicked. In FF and Safari it doesn't (they don't even call focus on the element!).

So I switched to an <a> , but even that is still broken in Safari.

Here is a demo of the issue, try in Chrome and then Safari:

 document.querySelector('a').addEventListener('click', () => { echoActiveEl(); }); function echoActiveEl() { document.querySelector('.active-el-tag').innerHTML = document.activeElement.tagName.toLowerCase(); } echoActiveEl(); 
 <a href="#blah">Click me</a> <p>Active element: <span class="active-el-tag"></span></p> 

How can I make Safari behave properly and call focus on the element so it becomes the activeElement? Doing element.focus() does nothing! Thanks.

Edit: e.currentTarget.focus() does actually work, e.target was pointing to a span I had in my <a> .

Since you need the onBlur event, you can archive what you want with something like this:

document.querySelector('a').addEventListener('blur', () => {
    var targetElement = event.target || event.srcElement;
    echoBluredEl(targetElement)
});

function echoBluredEl(ele) {
   document.querySelector('.blured-el-tag').innerHTML = ele.tagName.toLowerCase();
}

As far as manually putting focus is concerned i think it's an ES 6 support issue , try traditional syntax instead

document.querySelector('a').addEventListener('click', function(e) {

  //e.preventDefault();
  this.focus();
  document.querySelector('.active-el-tag').innerHTML = document.activeElement.tagName.toLowerCase();

});

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