JavaScript | focus()方法 (JavaScript | focus() Method)
The focus() method in DOM is used to give focus to an element. Its counterpart is blur() method which removes that particular element from focus. It does not take any parameters and doesn't have a return type.
DOM中的focus()方法用于为元素赋予焦点。 它的对应对象是blur()方法 ,该方法从焦点中删除该特定元素。 它不带任何参数,没有返回类型。
Example:
例:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Focus method</title>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<style>
body {
background: palegreen;
}
form {
position: absolute;
top: 50px;
left: 250px;
border: 2px solid white;
background: whitesmoke;
text-align: center;
padding: 12px;
margin: 12px;
width: 700px;
}
</style>
<body>
<div class="container">
<form action="">
<input type="text" name="Name" id="name" placeholder="Name">
<input type="email" name="Email" id="email" placeholder="Email">
<input type="password" name="Password" id="password" placeholder="Password">
<button class="btn">Submit form!</button>
</form>
</div>
</body>
<script>
</script>
</html>
Output
输出量
You can see that materialize styles its forms in such a way that when you click an input field, a blue underline appears underneath that field.
您可以看到以这种方式实现其样式的样式,使得当您单击输入字段时,该字段下方会出现一个蓝色下划线。
On clicking the password field, there’s a blue underline indicating that the field is in focus. We can set a field to focus without clicking it by triggering it an onmousemove event.
单击密码字段时,会有一个蓝色下划线指示该字段已对准焦点。 我们可以通过触发onmousemove事件来设置要聚焦的字段而无需单击它。
<input type="text" name="Name" id="name" placeholder="Name" onmousemove="focus()">
Now, when I move my mouse over the name input field, the onmousevent gets triggered and it fires the focus function due to which we see the little blue underline on the field.
现在,当我将鼠标移到名称输入字段上时 , onmousevent会被触发并触发聚焦功能,因此我们在该字段上看到蓝色的下划线。
翻译自: https://www.includehelp.com/code-snippets/focus-method-with-example-in-javascript.aspx