Div lost focus event implementation idea

  • 2020-03-30 02:43:37
  • OfStack

Here are a few events to look at in this article (from w3c).

Blur events: blur events occur when an element loses focus.

Focus event: the focus() method is used to give focus to a text field (or to some element).

TabIndex property: the tabIndex property sets or returns the TAB key control order of the button.

We all know that blur is only for form controls and that there is no way to trigger actions for span, div, li, etc. Now we just need to set a tabindex property to trigger their focus events.

Real project code:
 
Esc.PopupMenu.prototype._createPopup=function(){ 
var popupDiv = $('<div tabindex=1></div>'); //Create a div
popupDiv.appendTo(this._owner.element); //The div and span
var _popup=popupDiv[0]; 
_popup.hide=function(){ 
popupDiv.hide(); 
}, 
_popup.show=function(){ 
popupDiv.show(); 
popupDiv.focus();<span style="white-space:pre"> </span>//Let div get the focus
}; 
popupDiv.blur(function(){ 
popupDiv.hide(); 
}); 
return _popup; 
} 

What this code means is that I simulate a createPopup with div (IE can be generated directly), give it a tabindex property when it's generated, add a span, and then let it support hide and show. What's particularly noteworthy is that popupDiv,focus (), you have to give div a focus, otherwise it has no focus and how to lose focus.

Related articles: