"."/> ".">

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2022-03-10 12:11:343932browse

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">

JavaScript:

object.onfocus=function(){SomeJavaScriptCode}

JavaScript, use addEventListener() method:

object.addEventListener("focus", myScript);

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">

JavaScript:

object.onblur=function(){SomeJavaScriptCode};

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>

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!

Statement:
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