Summarize the focus management in Javascript in detail, and summarize the javascript focus

Source: Internet
Author: User

Summarize the focus management in Javascript in detail, and summarize the javascript focus

Focus Element

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

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

There is also a way to get the focus of non-form elements.tabIndexSet the property to-1 and then callfocus()Method

<Div id = "test" style = "height: 30px; width: 100px; background: lightgreen "> div </div> <button id =" btn "> div element obtains focus </button> <script> btn. onclick = function () {test. tabIndex =-1; test. focus ();} test. onfocus = function () {this. style. background = 'pink ';} </script>

ActiveElement

document.activeElementAttribute is used to manage the DOM focus and stores the elements that currently obtain the focus.

[Note] This attribute is not supported by IE

<Div id = "test" style = "height: 30px; width: 100px; background: lightgreen "> div </div> <button id =" btn "> div element obtains 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>

Focus

There are four ways for elements to get focus, including page loading, user input (press the tab key ),focus()Method andautofocusAttribute

[1] page loading

By default, when the document is loaded,document.activeElementThe reference of the body element is saved in. During document loading,document.activeElementIs null.

<script>console.log(document.activeElement);//null</script><body><script>console.log(document.activeElement);//<body></script></body>

[2] user input (press the tab key)

You can usually use the tab key to move the focus and use the space key to activate the focus. For example, if the focus is on a link, click the Space key to jump to the link.

The tab key cannot be mentionedtabindexAttribute.tabindexAttribute is used to specify whether the current HTML Element Node is traversed by the tab key and the traversal priority.

1. Iftabindex=-1, The tab key skips the current element.

2. Iftabindex=0The tab key traverses the current element. If an element is not settabindexThe default value is 0.

3. IftabindexIf the value is greater than 0, the tab key is preferentially traversed. A larger value indicates a smaller priority.

In the following code, when the tab key is used, the focus sequence of the button is 2, 5, 1, and 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()The method is used to set the browser's focus to the form field, that is, to activate the form field so that it can respond to Keyboard Events.

[Note] As mentioned earlier, if it is not a form element, set ittabIndex-1. You can also obtain the focus.

<Span id = "test1" style = "height: 30px; width: 100px; "> span </span> <input id =" test2 "value =" input "> <button id =" btn1 "> focus of a span element </button> <button id =" test2 "value =" input "> "btn2"> focus of input elements </button> <script> btn1.onclick = function () {test1.tabIndex =-1; test1.focus () ;}btn2.onclick = function () {test2.focus () ;}</script>

[4] autofocus

An HTML5 form field is added.autofocusProperty. If this property is set, the focus can be automatically moved to the corresponding field without javascript.

[Note] This attribute can only be used for form elements.tabIndex=”-1″It does not take effect either.

<input autofocus value="abc">

HasFocus ()

document.hasFocus()Method returns a Boolean value indicating whether any element in the current document is activated or focused. By checking whether the document gets the focus, you can see if it is interacting with the page.

Console. log (document. hasFocus (); // true // click another tab in two seconds to leave the focus from the current page setTimeout (function () {console. log (document. hasFocus (); // false}, 2000 );

No focus

If javascript is used to make the element lose focus, useblur()Method

blur()The function of the method is to shift the focus from the element. Before callingblur()When a method is used, the focus is not transferred to a specific element. Instead, the focus is removed from the element that calls the method.

<Input id = "test" type = "text" value = "123"> <button id = "btn1"> the input element obtains the focus </button> <button id = "btn2 "> the input element loses focus </button> <script> btn1.onclick = function () {test. focus ();} btn2.onclick = function () {test. blur () ;}</script>

Focus event

A focus event is triggered when the page gets or loses the focus. Use these events anddocument.hasFocus()Methods anddocument.activeElementAttribute combination to know the user's whereabouts on the page

Focus events include the following four

1. blur

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

2. focus

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

3. focusin

focusinThe event is triggered when the element gets the focus. This event correspondsfocusEvent is equivalent, but it bubbles

4. focusout

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

[Note] For focusin and focusout events, apart from the support for DOM0-level event handlers in IE, 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> <button id =" btn1 "> get focus for div elements whose content is 123 </button> <button id =" btn2 "> content the div element of 123 loses focus </button> <button id = "reset"> restore </button> <script> reset. onclick = function () {history. go ();} // focus () method btn1.onclick = function () {boxIn. tabIndex =-1; boxIn. focus ();} // 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';} if (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>

According to the running results,focusinEvents can be bubbling.blurEvents cannot bubble

Focus events are often used for form display and verification.

For example, when the focus is obtained, the background color is modified; when the focus is lost, the background color is restored and verified.

<Div id = "box"> <input id = "input1" type = "text" placeholder = "only numbers can be entered"> <input id = "input2" type = "text "placeholder =" only Chinese characters can be entered "> <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.tar get | e. srcElement; target. style . BackgroundColor = 'lightgreen';} function fnOut (e) {e = e | event; var target = e.tar get | e. srcElement; target. style. backgroundColor = 'initial'; // if it is a text box that verifies a number, if (target = input1) {if (! /^ \ D * $ /. test (target. value. trim () {target. focus (); tips. innerHTML = 'only numbers can be entered. Please enter 'settimeout (function () {tips. innerHTML = ''}, 500) ;}// if it is a text box for verifying Chinese characters if (target = input2) {if (! /^ [\ U4e00-\ u9fa5] * $ /. test (target. value. trim () {target. focus (); tips. innerHTML = 'only Chinese characters can be entered. Please enter 'settimeout (function () {tips. innerHTML = ''}, 500) ;}}</script>

Summary

The above is a summary of all the content of focus management in Javascript. This article is very detailed and has some reference value for your study and work, if you have any questions, you can leave a message.

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.