A detailed summary of focus management _javascript techniques in JavaScript

Source: Internet
Author: User

Focus Element

What elements can get the focus? By default, only the form element can get the focus. Because only form elements can interact

<input type= "text" value= "223" >

There is also a way to get focus on non-form elements by tabIndex setting the property to-1 before calling the focus() method

<div id= "test" style= "Height:30px;width:100px;background:lightgreen" >div</div>
<button id= "BTN" ">div element gets focus </button>
<script>
btn.onclick = function () {
 test.tabindex =-1;
 Test.focus (); 
}
Test.onfocus = function () {
 this.style.background = ' pink ';
}
</script>

Activeelement

document.activeElementproperty is used to manage DOM focus, holding the element that currently has the focus

[note] This property IE browser does not support

<div id= "test" style= "Height:30px;width:100px;background:lightgreen" >div</div>
<button id= "BTN" ">div element gets focus </button>
<script>
console.log (document.activeelement);//<body>
Btn.onclick = function () {
 console.log (document.activeelement);//<button>
 test.tabindex =-1;
 Test.focus (); 
 Console.log (document.activeelement);//<div>
}
</script>

Get focus

There are 4 ways that the element gets focus, including page load, user input (press TAB), focus() methods, and autofocus properties

"1" Page load

By default, a reference to the BODY element is saved when the document has just finished loading document.activeElement . document.activeElementthe value of the document during the load is null

<script>
Console.log (document.activeelement);//null
</script>
<body>
< Script>
Console.log (document.activeelement);//<body>
</script>
</body>

"2" User input (press TAB key)

Users can usually use the TAB key to move the focus and use the SPACEBAR to activate the focus. For example, if the focus is on a link, click the spacebar at this point, and then jump to the link

When it comes to the TAB key, you must mention the tabindex attribute. tabindexproperty is used to specify whether the current HTML element node is traversed by the TAB key, and the precedence of the traversal

1. If tabindex=-1 the TAB key skips the current element

2, if tabindex=0 , the TAB key will traverse the current element. If an element is not set tabindex , the default value is 0

3, if tabindex greater than 0, the TAB key is the first traversal. A larger value indicates a smaller priority

In the following code, when you use the TAB key, the button gets the focus in the order that 2, 5, 1, 3

<div id= "box" >
 <button tabindex= "3" >1</button>
 <button tabindex= "1" >2</button >
 <button tabindex= "0" >3</button>
 <button tabindex= "-1" >4</button>
 < Button tabindex= "2" >5</button> 
</div>
<script>
box.onkeyup = function () {
 Document.activeElement.style.background = ' pink ';
}
</script>

"3" focus ()

focus()method is used to set the browser's focus to a form field, that is, to activate a form field so that it responds to keyboard events

[note] As described earlier, tabIndex you can also get focus if it is not a form element, set to-1

<span id= "test1" style= "height:30px;width:100px;" >span</span>
<input id= "test2" value= "input" > <button id= "btn1" >span
element to gain focus </ button>
<button id= "btn2" >input element gets focus </button>
<script>
btn1.onclick = function ( ) {Test1.tabindex=-1;test1.focus ();}
Btn2.onclick = function () {Test2.focus ();}
</script>

"4" Autofocus

HTML5 a form field adds a autofocus property that, as long as you set this property, you can automatically move the focus to the field without JavaScript

[note] This property can only be used for form elements, and normal elements tabIndex=”-1″ do not take effect even if settings

<input Autofocus value= "ABC" >

Hasfocus ()

document.hasFocus()Method returns a Boolean value that indicates whether any elements in the current document are active or have focus. You can see if the document is interacting with the page by detecting whether it has been focused

Console.log (Document.hasfocus ())//true
//Click on another tab in two seconds to leave the focus out of the current page
settimeout (function () {
 Console.log (Document.hasfocus ());//false
},2000);

Lose focus

If you're using JavaScript to lose focus on an element, use the blur() method

blur()The purpose of the method is to remove the focus from the element. When a blur() method is invoked, the focus is not shifted to a particular element; it simply removes the focus from the element that invokes the method.

<input id= "Test" type= "text" value= "123" >
<button id= "btn1" >input elements get focus </button>
< Button id= "btn2" >input element loses focus </button>
<script>
btn1.onclick = function () {Test.focus ();}
Btn2.onclick = function () {Test.blur ();}
</script>

Focus Events

Focus events are triggered when the page gets or loses focus. Use these events and work with document.hasFocus() methods and document.activeElement attributes to know the whereabouts of the user on the page

A total of 4 focus events include the following

1, Blur

blurEvent is triggered when the element loses focus. This event will not bubble

2, focus

focusEvent is triggered when the element gets focus. This event will not bubble

3, Focusin

focusinEvent is triggered when the element gets focus. This event focus is equivalent to an event, but it bubbles

4, Focusout

focusourEvent is triggered when the element loses focus. This event is equivalent to the Blur event, but it bubbles

[note] regarding the Focusin and focusout events, except IE browsers support DOM0 level event handlers, other browsers only support DOM2 level event handlers

 <div id= "box" style= "Display:inline-block;padding:25px;background-color:lightgreen;" > <div id= "boxin" style= "Height:50px;width:50px;background-color:pink;" >123</div> </div> <button id= "BTN1" > content 123 div element get focus </button> <button id= "BTN2" > The div element with content 123 loses focus </button> <button id= "reset" > Restore </button> <script> reset.onclick = function ()
{History.go ();}
 The focus () method Btn1.onclick = function () {boxin.tabindex=-1;
Boxin.focus (); The//blur () method Btn2.onclick = function () {Boxin.blur ();}//focusin event if (boxin.addeventlistener) {Boxin.addeventlistener ( ' Focusin ', handler)}else{boxin.onfocusin = handler;} function handler () {This.style.backgroundColor = ' lightblue ';} i 
F (box.addeventlistener) {box.addeventlistener (' Focusin ', handler)}else{box.onfocusin = handler;}
Blur event function Fnblur () {this.style.backgroundColor = ' orange ';} Boxin.onblur = Fnblur;
Box.onblur = Fnblur; </script> 

It is known from the running result that focusin events can bubble; blur events are not bubbling.

Focus events are often used for form display and validation

For example, when you get the focus, modify the background color, restore the background color when you lose focus, and verify

<div id= "box" > <input id= "input1" type= "text" placeholder= "can only enter the number" > <input id= "input2" type= "text" Plac
 Eholder= "can only input Chinese characters" > <span id= "Tips" ></span> </div> <script> if (box.addeventlistener) {
 Box.addeventlistener (' Focusin ', fnin);
Box.addeventlistener (' Focusout ', fnout);
 }else{box.onfocusin = Fnin;
Box.onfocusout = Fnout;
 function Fnin (e) {e = e | | | event; var target = E.target | |
 E.srcelement;
Target.style.backgroundColor = ' LightGreen ';
 function Fnout (e) {e = e | | | event; var target = E.target | |
 E.srcelement;
 Target.style.backgroundColor = ' initial ';
 If it is the text box that validates the number (target = = input1) {if (!/^\d*$/.test (Target.value.trim ())) {Target.focus ();
 tips.innerhtml = ' can only enter numbers, please re-enter ' settimeout (function () {tips.innerhtml = '},500 ');
 }//If it is a text box that verifies Chinese characters (target = = Input2) {if (!/^[\u4e00-\u9fa5]*$/.test (Target.value.trim ())) {Target.focus (); tips.innerhtml = ' Can only enter Chinese characters, please re-enter ' settimeout (function () {tips.innerhtml = '},500 '); }} </script>

Summarize

The above is for you to sum up the focus of JavaScript management in all the content, this article introduces very detailed, to everyone's study and work has a certain reference value, if you have questions you can message exchange.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.