Home >Web Front-end >JS Tutorial >How javascript handles focus

How javascript handles focus

藏色散人
藏色散人Original
2021-10-18 14:11:542339browse

How to handle focus in JavaScript: 1. Obtain focus through the "field.focus();" method; 2. Handle the loss through the "o[i].blur = function(){...}" method focus.

How javascript handles focus

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

How does javascript handle focus?

JavaScript focus processing (get focus, lose focus blur)

Focus processing

Focus processing mainly includes focus (get focus) and blur (lost focus) event types. The so-called focus is to activate the form field so that it can respond to keyboard events.

Get focus: focus

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>

Lost focus: blur

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: for all input form elements The focus and blur event handlers are bound to set the element to be raised when it gains focus and sunk 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>

How javascript handles focus

Note: If the field is hidden (), or use CSS display and visibility to hide the field display. Setting it to gain focus will cause an exception.

Recommended study: "javascript basic tutorial"

The above is the detailed content of How javascript handles focus. 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