代码之家  ›  专栏  ›  技术社区  ›  Flux

如何永久聚焦元素?

  •  0
  • Flux  · 技术社区  · 7 年前

    假设我有一个页面,其中按钮或输入字段是页面上最重要的元素我知道通过使用 autofocus 属性:

    <button autofocus>Hello!</button>
    

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

    如何永久地聚焦html元素?

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

    编辑:我正在制作一个个人应用程序,页面上只有一个按钮,没有其他按钮。对焦将允许我在任何时候使用键盘(例如按回车键)快速“按下”按钮。

    3 回复  |  直到 7 年前
        1
  •  3
  •   T.J. Crowder    7 年前

    请看 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.

    或者使用间隔计时器等。

        2
  •  0
  •   jcubic    7 年前

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

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

    注意评论中的警告。

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

    在某种程度上,您可以使用css来实现这一点,还可以:

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