HTMLElement.focus

概述

 HTMLElement.focus()方法可以设置指定元素获取焦点。

语法

element.focus();

示例

text输入框获取焦点

JavaScript

focusMethod = function getFocus() {           
  document.getElementById("myTextField").focus();
}

HTML

<input type="text" id="myTextField" value="Text field.">
<p></p>
<button type="button" onclick="focusMethod()">点击我让输入框获取焦点</button>

Result

按钮获取焦点

JavaScript

focusMethod = function getFocus() {          
  document.getElementById("myButton").focus();
}

HTML

<button type="button" id="myButton">Click Me!</button>
<p></p>
<button type="button" onclick="focusMethod()">点击我让按钮获取焦点</button>

Result

规范

Specification Status Comment
WHATWG HTML Living Standard
focus
Living Standard  
HTML5.1
focus
Recommendation  
HTML5
focus
Recommendation  
Document Object Model (DOM) Level 2 HTML Specification
focus
Recommendation  
Document Object Model (DOM) Level 1 Specification
focus
Recommendation  

提示

如果点击事件使用HTMLElement.focus()方法,需要使用event.preventDefault()来让焦点移除当前dom。

规范

DOM Level 1 HTML: various elements.focus

DOM Level 2 HTML: various elements.focus

相关链接

文档标签和贡献者

 此页面的贡献者: slimeball, teoli, khalid32, ziyunfei
 最后编辑者: slimeball,