简体   繁体   中英

Are the 'blur' and 'focus' events guaranteed to occur in that order?

Say you press tab to move focus from element A to B. This should fire the following:

  1. blur on element A
  2. focus on element B

Is it safe to assume they will fire in that order?

blur :

A user agent MUST dispatch this event when an event target loses focus. The focus MUST be taken from the element before the dispatch of this event type.

focus :

A user agent MUST dispatch this event when an event target receives focus. The focus MUST be given to the element before the dispatch of this event type.

Since no two elements can have focus at the same time, it stands to reason that blur must occur before focus .

Run the below snippet and focus the input on the left, then click into the input on the right and you will see that the order is blur -> focusout -> focus, (in Chrome), but if you check it in Safari, it will be blur -> focusout -> focus. So now, you can not assume that different user agents implement the same event order. Also, focusout and blur are essentially the same thing. The difference is, the blur event does not bubble.

Edit: In response to your edit, yes blur will always occur before focus.

 var i1 = document.getElementById("i1"); var i2 = document.getElementById("i2"); var whatHappened = document.getElementById("whatHappened"); i1.addEventListener("focusout", function() { var p = document.createElement("P"); p.innerText = "focusout"; whatHappened.appendChild(p); }); i1.addEventListener("blur", function() { var p = document.createElement("P"); p.innerText = "blur"; whatHappened.appendChild(p); }); i2.addEventListener("focus", function() { var p = document.createElement("P"); p.innerText = "focus"; whatHappened.appendChild(p); }); 
 <input type="text" id="i1" /> <input type="text" id="i2" /> <div id="whatHappened"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM