Focus Event:
Not all elements have focus events, only elements that are interactive, such as form elements, a tags. Only one element in the page has focus, one focus, and the other is lost, and the document is defaulted.
The example structure is as follows:
<form>
<input type= "text" name= "txt1" id= "txt"/>
<input type= "button" Name= "BTN" value= "click"/>
</form>
JS operation is as follows:
1.form.txt1.focus (); This method does not trigger the onfocus () event If the element has the focus.
2.form.txt1.onfocus=function () {console.log (1); }// The event is triggered when the element receives focus
3.form.txt1.onblur=function () {console.log (2);} Triggers the event when the element loses focus
4.form.btn.onclick=function () { form.txt1.select (); }//Select all text in the input box
5.form.btn.onclick=function () {form.txt1.setSelectionRange (2,5); Form.txt1.focus ();} //Setselectionrange need to be used with focus () to see the effect, where the end position of Setselectionrange is not included, Setselectionrange (Start,end) contains two parameters, One is start: the starting position; one is end: End position.
By default, the text in the input box is selected with the text color blue, and if you want to change the background color, you can use #txt:: selection{ background:pink; } to change
Focus Defocus event for form in JS