How to detect `focusin` support?

前端 未结 3 2031
天命终不由人
天命终不由人 2020-12-30 06:44

Thanks to Perfection kills, we can use the following JavaScript to detect event support:

function hasEvent(ev) {
    var elem = document.createElement(\'a\'),         


        
3条回答
  •  梦毁少年i
    2020-12-30 06:58

    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).

提交回复
热议问题