Javascript blur-click not working together

2019-05-24 12:35发布

问题:

I have the following code:

HTML:

<input type='text' class='a' />
<div class='inst' tag='a'></div>
<input type='text' class='b' />
<div class='inst' tag='b'></div>
<input type='text' class='c' />
<div class='inst' tag='c'></div>

JS:

$(function() {
    $('.inst').click(function() {
        alert($(this).attr('tag') + ' clicked');
    });

    $('[type=text]').focus(function() {
       show_inst($(this).attr('class'));
    }).blur(function() {
       //hide_inst($(this).attr('class'));
    });

    function show_inst(tag) {
        $('div.inst[tag=' + tag + ']').html(tag + ' instructions');
    }

    function hide_inst(tag) {
        $('div.inst[tag=' + tag + ']').html('');
    }
});

CSS:

.inst {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    cursor: pointer;
}

It works fine: when inst is clicked I see the alert message, and when the input becomes focused the instruction appears.

Now I want the not relevant instruction to disappear on blur. So I tried to add the commented line inside blur(). It does not work like that because blur() is called first and removes the instruction, so if I click on the instruction - nothing happens.

How could I solve this?

回答1:

If your only issue is that the instruction is hidden before the click on it is issued, consider adding a tiny delay. This will basically cause your hide instruction to be executed after the click is processed.

Something like this:

$('[type=text]').focus(function() {
   show_inst($(this).attr('class'));
}).blur(function() {
   setTimeout(function(){
     hide_inst($(this).attr('class'));
   }, 50); // make this happen after any other events
});


回答2:

        var timeoutId;
        $('[type=text]').on("blur", function(){
            timeoutId = setTimeout(function(){                     
                console.log("blur");
            }, 50);
        }).on("focus", function(){
            clearTimeout(timeoutId);
        });

Or you can try this, it will fire blur only when you leave the input (the "false" click is removed by clearTimeout).