Preface: Sometimes you need to get which element the page focus is on. The focus can be used to determine whether the user is operating the page and other information. It was not convenient before because you had to record it yourself. 1. The default focus is on the bodyAfter the page loads, document.activeElement is on body: console.log(document.activeElement); // Console print: //body 2. Manually get the focus of the text boxThe most common way to get focus is with form elements. Here we take a text box as an example: <input type="text" id="name" /> When you put the cursor in the text box, view the document.activeElement: It is the text box that gets the focus above. 3. Get focus through focus In addition to manually placing it in the text box to let the text box get the focus, you can also use <input type="text" id="name" /> <script type="text/javascript"> // Get the angle of the text box document.querySelector("#name").focus(); console.log(document.activeElement); // Firefox browser console prints: // <input id="name" type="text"> </script> 4. Tab switch focusYou can switch focus through tab on the web page. Let’s try another button: <input type="text" id="name" /> <button>Click me</button> To facilitate viewing the effect, set a timer to print document.activeElement after 5 seconds: setTimeout(() => { console.log(document.activeElement); // Firefox browser console prints: // <button> }, 5000); Visit the page, switch to the button via tab, and then view the console output: Tab switch focus: 5. document.hasFocus() determines whether to obtain focusSimilarly set the timer to view: setTimeout(() => { console.log(document.hasFocus()); }, 5000);
This is the end of this article about the You may also be interested in:
|
<<: Set the width of the table to be fixed so that it does not change with the text
Table of contents Overview Single file components...
You know that without it, the browser will use qui...
In development, it is often necessary to cache th...
.imgbox{ width: 1200px; height: 612px; margin-rig...
In-depth understanding of this in Js JavaScript s...
Since I used this plugin when writing a demo and ...
Event response refresh: refresh only when request...
HTML tag: superscript In HTML, the <sup> tag...
1. Delete folders Example: rm -rf /usr/java The /...
1. Installation process MySQL version: 5.7.18 1. ...
This article shares the specific code of JQuery t...
Overview es6 adds a new way to get specified elem...
1. Document flow and floating 1. What is document...
Table of contents Easy to use Create a project vu...
Table of contents Enter the topic mysql add, dele...