문제

Let's consider simple HTML input field

<input type="text" onblur='alert("hello");' />

when mouse is in this input field and you try to open new tab in browser (Chrome, IE, ...), onblur event is being triggered. I don't want to trigger onblur event in such manner. How can I avoid this?

도움이 되었습니까?

해결책

You can use document.activeElement to check if the element has indeed lost focus in DOM. (Browser compatibility is quite wide as well.)

Your code could look like this:

HTML

<input type="text" onblur='blurred(this);' />

JS

function blurred(elem) {
    if (elem != document.activeElement) {
        alert("Bye !");
    }
}

See, also, this short demo.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top