如何永久关注某个元素?

时间:2019-04-24 14:34:17

标签: javascript html html5

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

<button autofocus>Hello!</button>

这与广告一样工作,但是不幸的是,如果用户单击页面的任何其他部分,HTML元素将失去焦点。

如何永久聚焦HTML元素?

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

编辑:我正在制作一个个人应用程序,其中页面上永远只有一个按钮,而没有其他按钮。焦点使我可以随时使用键盘快速“按”按钮(例如,按Enter键)。

3 个答案:

答案 0 :(得分:3)

请参阅my comment。我强烈建议您不要在一般情况下这样做,但是您的声音听起来像是在良好控制的环境中的一个特定情况。

您可以将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.

或使用间隔计时器等

答案 1 :(得分:0)

我认为唯一的选择就是这样的JavaScript:

var button = document.querySelector('button');
document.addEventListener('click', function(e) {
  if(!e.target.matches('button[autofocus]')) {
    button.focus();
  }
})
<button autofocus>focus</button>

答案 2 :(得分:0)

注意评论中的警告。

document.getElementById('stayHere').addEventListener('blur', function() {
    this.focus();
});

您还可以在某种程度上使用CSS进行此操作,

body {
    pointer-events: none;
}
.greedy-button {
    pointer-events: auto;
}