Home > Web Front-end > Front-end Q&A > How to determine if an element has focus in javascript

How to determine if an element has focus in javascript

WBOY
Release: 2022-03-10 12:11:34
Original
3922 people have browsed it

In JavaScript, you can use onfocus() and onblur() events to determine whether an element has focus. The onfocus event occurs when an element gains focus, and the onblur event occurs when an element loses focus. The syntax is "".

How to determine if an element has focus in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How does javascript determine whether an element has focus?

The onfocus event occurs when the object gains focus.

Onfocus is usually used for ,

Tip: The opposite event of the onfocus event is the onblur event.

Syntax

HTML:

<element onfocus="SomeJavaScriptCode">
Copy after login

JavaScript:

object.onfocus=function(){SomeJavaScriptCode}
Copy after login

JavaScript, use addEventListener() method:

object.addEventListener("focus", myScript);
Copy after login

onblur The event occurs when the object loses focus.

Onblur is often used for Javascript verification code, generally used in form input boxes.

Tip: The opposite event of onblur is the onfocus event.

Syntax

HTML:

<element onblur="SomeJavaScriptCode">
Copy after login

JavaScript:

object.onblur=function(){SomeJavaScriptCode};
Copy after login

The example is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
function Function(){
document.getElementById(&#39;tip&#39;).innerHTML=&#39;元素失去焦点了&#39;;
}
function myFunction(x){
document.getElementById(&#39;tip&#39;).innerHTML=&#39;元素获取焦点了&#39;;
}
</script>
</head>
<body>
判断焦点示例: <input type="text" onfocus="myFunction(this)" onblur="Function()">
<p id="tip" style="color:red;"></p>
</body>
</html>
Copy after login

Output result:

How to determine if an element has focus in javascript

Related recommendations: javascript learning tutorial

The above is the detailed content of How to determine if an element has focus in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template