首页 > 解决方案 > 如何永久聚焦一个元素?

问题描述

假设我有一个页面,其中按钮或输入字段是页面上最重要的元素。我知道我可以通过使用autofocus属性在页面加载时自动聚焦元素:

<button autofocus>Hello!</button>

这就像宣传的那样有效,但不幸的是,如果用户单击页面的任何其他部分,HTML 元素将失去焦点。

如何永久聚焦 HTML 元素?

(注意:如果确实需要使用 JavaScript 来完成此任务,请使用纯 JavaScript [即不使用 jQuery] 显示解决方案)。

编辑:我正在制作一个个人应用程序,页面上只有一个按钮,没有别的。焦点将允许我随时使用键盘快速“按下”按钮(例如通过按下回车键)。

标签: javascripthtml

解决方案


请看我的评论。我强烈建议不要在一般情况下这样做,但在控制良好的环境中,你的情况听起来像是一个非常特殊的情况。

您可以将事件挂钩到blur按钮上并尝试再次使其获得焦点:

document.querySelector("button[autofocus]").addEventListener("blur", function() {
    var t = this;
    t.focus();
    setTimeout(function() { // Some browsers won't let you do it until
        t.focus();          // after the blur has completed
    }, 100);
});
<button autofocus>This is the button</button>
<button>Another button</button> just so we can see that it works if we tab away from the first one.

或者使用间隔计时器等。


推荐阅读