HTMLElement.focus() - Web API 接口参考 编辑

HTMLElement.focus() 方法用于设置焦点,如果被指定的元素可以获取到焦点,焦点就会被设置到该元素上。得到焦点的元素会作为键盘导航时的当前元素/基准元素,也会接收到相应的键盘事件等事件。

语法

element.focus(options); // Object parameter

参数

options 可选
An optional object providing options to control aspects of the focusing process. This object may contain the following property:
preventScroll 可选
A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur.

示例

将焦点设置到文本框上

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>

结果

将焦点设置到按钮上

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>

结果

Focus with focusOption

JavaScript

focusScrollMethod = function getFocus() {
  document.getElementById("myButton").focus({preventScroll:false});
}
focusNoScrollMethod = function getFocusWithoutScrolling() {
  document.getElementById("myButton").focus({preventScroll:true});
}

HTML

<button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button>
<button type="button" onclick="focusNoScrollMethod()">Click me to focus on the button without scrolling!</button>

<div id="container" style="height: 1000px; width: 1000px;">
<button type="button" id="myButton" style="margin-top: 500px;">Click Me!</button>
</div>

结果

规范

规范状态备注
HTML Living Standard
focus
Living Standard
HTML 5.1
focus
Recommendation
HTML5
focus
Recommendation
Document Object Model (DOM) Level 2 HTML Specification
focus
Obsolete
Document Object Model (DOM) Level 1 Specification
focus
Obsolete

备注

  • If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement
  • Behaviour of the focus in relation to different HTML features like tabindex or shadow dom, which previously remained under-specified, were recently updated (as October of 2019). Checkout WHATWG blog for more info.

浏览器兼容性

BCD tables only load in the browser

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

参见

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:51 次

字数:7433

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文