HTML DOM focus() 方法用于为 HTML 元素提供焦点。焦点不能应用于所有 HTML 元素。例如:您不能聚焦 <p> 标签。要从元素中移除焦点,请使用 blur() 方法。
用法
以下是语法 -
HTMLElementObject.focus()
示例
让我们看一个 focus() 方法的例子 -
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text]:focus, p:active {
color:blue;
font-size:35px;
background-color:lightpink;
border:2px solid blue;
}
input[type=text]{
color:black;
font-size:20px;
}
</style>
<script>
function enableFocus() {
document.getElementById("USR1").focus();
}
function disableFocus() {
document.getElementById("USR1").blur();
}
</script>
</head>
<body>
<h1>focus() method example</h1>
<label>USERNAME:<input id="USR1" type="text" size=5 maxlength=10></label>
<br><br>
<input type="button" onclick="enableFocus()" value="FOCUS">
<input type="button" onclick="disableFocus()" value="BLUR">
</body>
</html>
输出
这将产生以下输出 -
单击 FOCUS 按钮时 -
单击“模糊”按钮 -
在上面的例子中 -
我们首先创建了一个文本框,id 为 “USR1”,size 和 maxlength 属性值分别等于 5 和 10。
<label>USERNAME:<input id="USR1" type="text" size=5 maxlength=10></label>
当文本框处于焦点、活动和不处于焦点时,我们创建了两种不同的 css 样式 -
input[type=text]:focus, input[type=text]:active { color:blue; font-size:35px; background-color:lightpink; border:2px solid blue; } input[type=text]{ color:black; font-size:20px; }
然后我们创建了两个按钮 FOCUS 和 BLUR,当用户单击它们时,它们将分别执行 enableFocus() 和 disableFocus() 方法 -
<input type="button" onclick="enableFocus()" value="FOCUS"> <input type="button" onclick="disableFocus()" value="BLUR">
enableFocus() 方法使用 getElementById() 方法获取 “text” 类型的输入元素,并启用其 focus() 方法将焦点设置在文本框上,这将我们的:focus 样式应用于我们的文本框。 disableFocus() 方法获取 ID 为 “USR1” 的输入元素并在其上调用 blur() 方法,该方法从文本框中移除焦点,该文本框将我们的普通 css 样式应用于它,即它返回到默认样式 -
function enableFocus() { document.getElementById("USR1").focus(); } function disableFocus() { document.getElementById("USR1").blur(); }
相关用法
- HTML DOM fullscreenEnabled()用法及代码示例
- HTML DOM Style overflowY属性用法及代码示例
- HTML DOM Document hidden属性用法及代码示例
- HTML DOM IFrame用法及代码示例
- HTML DOM Textarea cols属性用法及代码示例
- HTML DOM Style pageBreakAfter属性用法及代码示例
- HTML DOM Base href属性用法及代码示例
- HTML DOM Pre用法及代码示例
- HTML DOM Input Month用法及代码示例
- HTML DOM Video canPlayType()用法及代码示例
- HTML DOM Range deleteContents()用法及代码示例
- HTML DOM console.dirxml()用法及代码示例
- HTML DOM Style transition属性用法及代码示例
- HTML DOM Video volume属性用法及代码示例
- HTML DOM Input Range用法及代码示例
- HTML DOM Style outlineOffset属性用法及代码示例
- HTML DOM Storage setItem()用法及代码示例
- HTML DOM TableHeader用法及代码示例
- HTML DOM Style maxWidth属性用法及代码示例
- HTML DOM NodeIterator whatToShow属性用法及代码示例
注:本文由纯净天空筛选整理自AmitDiwan大神的英文原创作品 HTML DOM focus() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。