当孩子获得焦点时触发模糊事件

时间:2016-04-25 08:19:34

标签: javascript html javascript-events focus blur

我需要在项目失去焦点时执行某些操作

基本上我有类似的东西

<div tabindex="1">
    <h1>title 1</h1>
</div>

<div tabindex="2">
    <h1>title 2</h1>

    <textarea></textarea>
</div>

JS:

$('div').blur((e) => { console.log('blur');});

DEMO

现在,当您在div之间切换时,它就像魅力一样,但当第二个div具有焦点时,您单击子文本区域会触发blur事件。这不是我想要的,因为我们仍然在同一个div中。如何修复此问题,以便当点击位于div之外时仅触发模糊事件?

1 个答案:

答案 0 :(得分:1)

a element has been focus then the last element focused will trigger event 'blur'. You may have to design a hack for it...something like:

$('div').blur((e) => {
    setTimeout(function() {
        if(!$('textarea').is(':focus')){
            console.log('blur');
        }
    }, 100);
});

setTimeout is important because blur event being trigged in the first then focus event.