在本教程中,我们将学习如何使用JavaScript在页面加载时设置一个输入元素的焦点。
考虑一下,我们的HTML中有如下的input 元素。
<input id="name" placeholder="Name"/>
为了在页面加载时设置输入元素的焦点,我们可以在窗口发生load 事件时调用输入元素的focus() 方法。
下面是一个例子。
const input = document.getElementById("name");
// fires when a page is loaded fully
window.addEventListener("load", (e)=>{
input.focus(); // adding the focus
})
在上面的例子中,首先我们使用document.getElement() 方法访问了JavaScript中的HTMLinput 元素。
接下来,我们在window 对象上添加了加载事件监听器,在里面我们调用了input.focus() 方法。因此,当一个页面被完全加载时,它将焦点设置为一个选定的输入元素。
我们使用了HTMLElement.focus()方法来设置一个选定元素的焦点。
input.focus();
focus() 方法将键盘焦点设置在它被调用的元素上。
完整的工作实例
<input id="name" placeholder="Name"/>
JavaScript。
const input = document.getElementById("name");
// fires when a page is loaded fully
window.addEventListener("load", (e)=>{
input.focus(); // adding the focus
})
如果你想移除一个输入元素的焦点,请使用blur() 方法。
input.blur();