在JavaScript中点击按钮时移除焦点的方法

844 阅读1分钟

在本教程中,我们将学习如何使用JavaScript在点击时移除按钮的焦点。

考虑一下,在我们的HTML中,有如下的button 元素。

<button id="btn">Search</button>

要想在点击时从按钮上移走焦点,可以在按钮click 事件处理方法中调用blur() 方法。

下面是一个例子。

const btn = document.getElementById("btn");

btn.addEventListener("click", ()=>{
    btn.blur(); // removes the focus
})

在上面的例子中,首先我们使用document.getElementById() 来访问JavaScript中的按钮元素,然后我们使用addEventListener() 方法为按钮添加一个点击事件监听器。

因此,每当用户点击按钮时,它就会运行btn.blur() 方法并移除焦点。

如果你想在不选择当前活动元素的情况下移除其焦点,可以在document.activeElement 属性上调用blur()

下面是一个例子。

document.activeElement?.blur();

document.activeElement属性返回当前拥有焦点的dom中的元素。

完整的工作实例。

<button id="btn">Search</button>

JavaScript。

const btn = document.getElementById("btn");

btn.addEventListener("click", ()=>{
    btn.blur(); // removes the focus
})