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 "
".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
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('tip').innerHTML='元素失去焦点了'; } function myFunction(x){ document.getElementById('tip').innerHTML='元素获取焦点了'; } </script> </head> <body> 判断焦点示例: <input type="text" onfocus="myFunction(this)" onblur="Function()"> <p id="tip" style="color:red;"></p> </body> </html>
Output result:
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!