This article will introduce to you how to gain focus and lose focus in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Focus processing mainly includes focus (acquiring focus) and blur (losing focus) event types. The so-called focus is to activate the form field so that it can respond to keyboard events.
This event is triggered when you click or use the Tab key to switch to a form element or hyperlink object. The focus event is a way to determine the current position of the mouse within the page. By default, the entire document is in focus, but you can change the focus position by clicking or using the Tab key. '
Example: After the page has loaded, transfer focus to the first text box field in the form, preparing it to receive user input
<form id="myform" method="post" action="#"> 姓名<input type="text" name="name"/><br> 密码<input type="password" name="pass" /></form><script> var form = document.getElementById("myform"); var field = form.elements("name"); window.onload = function(){ field.focus(); }</scriipt>
The blur event type represents a response when the element loses focus. It corresponds to the focus event type and mainly affects form elements and hyperlink objects.
Example: Focus and blur are bound to all input form elements. Event handler function, set the element to be raised when it gains focus and sunken when it loses focus
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="text" /> <input type="text" /> <script> var o = document.getElementsByTagName("input"); for(var i = 0; i < o.length; i++){ o[i].onfocus = function(){ this.style.borderStyle = "outset"; } o[i].blur = function(){ this.style.borderStyle = "inset"; } } </script> </body></html>
javascript advanced tutorial]
The above is the detailed content of How JavaScript gets and loses focus. For more information, please follow other related articles on the PHP Chinese website!