Chrome (maybe Safari?) fires “blur” twice on input fields when browser loses focus

前端 未结 7 1987

Here is an interesting jsfiddle.

In Firefox:

  1. Run the fiddle
  2. Click in text input
  3. Click somewhere else. Should say \"1 bl
相关标签:
7条回答
  • 2020-12-28 16:25

    This probably isn't what you want to hear, but the only way to do it seems to be to manually track whether the element is focused or not. For example (fiddle here):

    var blurCount = 0;
    document.getElementsByTagName('input')[0].onblur = function(e) {
        if (!e) e = window.event;
        console.log('blur', e);
        if (!(e.target || e.srcElement)['data-focused']) return;
        (e.target || e.srcElement)['data-focused'] = false;
        document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
    };
    document.getElementsByTagName('input')[0].onfocus = function(e) {
        if (!e) e = window.event;
        console.log('focus', e);
        (e.target || e.srcElement)['data-focused'] = true;
    };
    

    Interestingly, I couldn't get this to work in jQuery (fiddle here) ... I really don't use jQuery much, maybe I'm doing something wrong here?

    var blurCount = 0;
    $('input').blur(function(e) {
        console.log('blur', e);
        if (!(e.target || e.srcElement)['data-focused']) return;
        (e.target || e.srcElement)['data-focused'] = false;
        $('div').innerHTML = (++blurCount + ' blurs');
    });
    $('input').focus(function(e) {
        console.log('focus', e);
        (e.target || e.srcElement)['data-focused'] = true;
    });
    

    You could also try comparing the event's target with document.activeElement. This example will ignore the alt+tab blur events, and the blur events resulting from clicking on Chrome's... chrome. This could be useful depending on the situation. If the user alt+tabs back into Chrome, it's as if the box never lost focus (fiddle).

    var blurCount = 0;
    document.getElementsByTagName('input')[0].onblur = function(e) {
        if (!e) e = window.event;
        console.log('blur', e, document.activeElement, (e.target || e.srcElement));
        if ((e.target || e.srcElement) == document.activeElement) return;
        document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
    };​
    ​
    
    0 讨论(0)
提交回复
热议问题