使用JavaScript将焦点设置在一个元素上的方法

469 阅读1分钟

在本教程中,我们将学习如何使用JavaScript为一个HTML元素设置焦点。

考虑一下,在我们的HTML中,有以下input 元素。

<input id="name" placeholder="Name"/>

要将焦点设置到一个元素上,首先我们需要在JavaScript中使用document.getElementById() 方法访问该元素。

const input = document.getElementById("name");

现在,对它调用一个focus() 方法。

// sets the focus to an input element
input.focus();

在上面的例子中,我们使用了HTMLElement.focus()方法来设置一个选定元素的焦点。

focus() 方法将键盘焦点设置在它被调用的元素上。

完整的工作实例。

<input id="name" placeholder="Name"/>

JavaScript。

const input = document.getElementById("name");

// sets the focus to an input element
input.focus();