Home > Web Front-end > JS Tutorial > body text

How JavaScript gets and loses focus

醉折花枝作酒筹
Release: 2021-04-29 09:17:37
forward
4263 people have browsed it

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.

How JavaScript gets and loses focus

Focus processing

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.

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>
Copy after login

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: 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>
Copy after login

How JavaScript gets and loses focus

##Note: If the field is hidden ([Recommended learning:

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!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!