How to detect `focusin` support?

删除回忆录丶 提交于 2019-11-30 06:49:38

This uses the fact that calling focus() triggers focusin: http://jsfiddle.net/pimvdb/YXeD3/.

The element must be visible and inserted into the DOM, otherwise focusin is not fired for some reason.

var result = (function() {
    var hasIt = false;

    function swap() {
        hasIt = true; // when fired, set hasIt to true
    }

    var a = document.createElement('a'); // create test element
    a.href = "#"; // to make it focusable
    a.addEventListener('focusin', swap, false); // bind focusin

    document.body.appendChild(a); // append
    a.focus(); // focus
    document.body.removeChild(a); // remove again

    return hasIt; // should be true if focusin is fired
})();

focusin & focusout should be fired BEFORE target element receives focus, event order is also seems buggy

http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order

currently, only IE works according to spec:

Chrome/Safari:
focus
focusin
DOMFocusIn
blur
focusout
DOMFocusOut
focus
focusin
DOMFocusIn

Opera 12:
focus
DOMFocusIn
focusin
blur
DOMFocusOut
focusout
focus
DOMFocusIn
focusin

IE 8:
focusin
focus
focusout
focusin
blur
focus

Firefox 14:
focus
blur
focus

You can test for ("onfocusin" in document).

This method has the advantage of being light and unobtrusive and it will tell you whether the browser supports the focusin event. (not on Chrome, sorry)

You may use the following code to get the same behaviour as the focusin event on all browsers (IE9+, Chrome, Firefox, Edge):

var eventName, useCapture;
if ("onfocusin" in document) {
  eventName = "focusin";
  useCapture = false;
} else {      
  eventName = "focus";
  useCapture = true;
}

document.body.addEventListener(eventName, function( event ) {
    event.target.style.background = "pink";    
  }, useCapture);

JS fiddle here: https://jsfiddle.net/d306qm92/2/

More information about the Firefox workaround here: https://developer.mozilla.org/en-US/docs/Web/Events/focus#Event_delegation

UPDATE: As said above, the test will wrongly say "false" on Chrome, nonetheless the code sample will work as intended as Chrome supports both methods (focusin and focus with useCapture).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!