--- title: HTMLElement.focus() slug: Web/API/HTMLElement/focus tags: - API - 参考 - 方法 - 焦点 translation_of: Web/API/HTMLOrForeignElement/focus ---
HTMLElement.focus()
方法用于设置焦点,如果被指定的元素可以获取到焦点,焦点就会被设置到该元素上。得到焦点的元素会作为键盘导航时的当前元素/基准元素,也会接收到相应的键盘事件等事件。
element.focus(options); // Object parameter
options
{{optional_inline}}preventScroll
{{optional_inline}}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.focusMethod = function getFocus() { document.getElementById("myTextField").focus(); }
<input type="text" id="myTextField" value="Text field."> <p></p> <button type="button" onclick="focusMethod()">点这里将焦点设置到文本框上!</button>
{{ EmbedLiveSample('Focus_on_a_text_field') }}
focusMethod = function getFocus() { document.getElementById("myButton").focus(); }
<button type="button" id="myButton">Click Me!</button> <p></p> <button type="button" onclick="focusMethod()">点这里将焦点设置到按钮上!</button>
{{ EmbedLiveSample('Focus_on_a_button') }}
focusScrollMethod = function getFocus() { document.getElementById("myButton").focus({preventScroll:false}); } focusNoScrollMethod = function getFocusWithoutScrolling() { document.getElementById("myButton").focus({preventScroll:true}); }
<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>
{{ EmbedLiveSample('Focus_prevent_scroll') }}
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('HTML WHATWG', 'editing.html#dom-focus', 'focus')}} | {{Spec2('HTML WHATWG')}} | |
{{SpecName('HTML5.1', 'editing.html#focus()-0', 'focus')}} | {{Spec2('HTML5.1')}} | |
{{SpecName('HTML5 W3C', 'editing.html#dom-focus', 'focus')}} | {{Spec2('HTML5 W3C')}} | |
{{SpecName('DOM2 HTML', 'html.html#ID-32130014', 'focus')}} | {{Spec2('DOM2 HTML')}} | |
{{SpecName('DOM1', 'level-one-html.html#method-focus', 'focus')}} | {{Spec2('DOM1')}} |
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 {{HTMLAttrxRef("tabindex")}} or {{Glossary("shadow tree","shadow dom", 1)}}, which previously remained under-specified, were recently updated (as October of 2019). Checkout WHATWG blog for more info.
{{Compat("api.HTMLElement.focus")}}