Create event observer for focus?

前端 未结 2 561
难免孤独
难免孤独 2021-02-01 20:29

Is it possible to have focus events bubble in protoype?

I am trying to prevent having to assign an observer on every input element.



        
相关标签:
2条回答
  • 2021-02-01 20:58

    focus and blur events don't bubble.

    You can fire event-handler during capturing phase. When using standard DOM methods, you would write

    document.addEventListener('focus',function(e){/*some code */}, true);
    

    the 'true' value is here most important.

    The problem is that IE doesn't support capturing phase of event propagation, but for IE you can use focusin and focusout events, which - unlike focus and blur events - do bubble. I recommend reading an article on this topic written by Peter Paul Koch. Other browsers (Firefox, Opera, Safari) probably (I didn't test it) support events like DOMFocusIn, DOMFocusOut which are equivalents for IE's focusin and focusout events.

    0 讨论(0)
  • 2021-02-01 21:02

    You can use this :

    function focusInHandler(event){
        Event.element(event).fire("focus:in");
    }
    function focusOutHandler(event){
        Event.element(event).fire("focus:out");
    }
    
    if (document.addEventListener){
        document.addEventListener("focus", focusInHandler, true);
        document.addEventListener("blur", focusOutHandler, true);
    } else {
        document.observe("focusin", focusInHandler);
        document.observe("focusout", focusOutHandler);
    }
    
    document.observe('focus:in', function(event) {
        // Your code
    });
    

    My jsFiddle : http://jsfiddle.net/EpokK/k7RPE/3/

    0 讨论(0)
提交回复
热议问题