javascript - 如何永久聚焦一个元素?
问题描述
假设我有一个页面,其中按钮或输入字段是页面上最重要的元素。我知道我可以通过使用autofocus
属性在页面加载时自动聚焦元素:
<button autofocus>Hello!</button>
这就像宣传的那样有效,但不幸的是,如果用户单击页面的任何其他部分,HTML 元素将失去焦点。
如何永久聚焦 HTML 元素?
(注意:如果确实需要使用 JavaScript 来完成此任务,请使用纯 JavaScript [即不使用 jQuery] 显示解决方案)。
编辑:我正在制作一个个人应用程序,页面上只有一个按钮,没有别的。焦点将允许我随时使用键盘快速“按下”按钮(例如通过按下回车键)。
解决方案
请看我的评论。我强烈建议不要在一般情况下这样做,但在控制良好的环境中,你的情况听起来像是一个非常特殊的情况。
您可以将事件挂钩到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.
或者使用间隔计时器等。
推荐阅读
- reactjs - eslint-plugin-react-hooks 出现意外错误(react-hooks/exhaustive-deps)
- json - 使用 Asp.net MVC Core 3.1 的 JsonResult 的正确代码是什么?
- r - 使用 cumsum 在 ggplot 中绘图
- database - 使用另一个表中的非空值更新 sqlite 表
- java - @JsonTypeName 不起作用并在尝试解析子类型时返回 Missing type id
- twitter - 是否可以按关注者数量搜索 Twitter 用户?
- development-environment - 从 CS50 开发环境迁移
- c - 偏航旋转:基于零的 mins/maxs 重新计算 mins/maxs
- php - 通过 PHP 从 csv 文件返回第一个结果
- bulletphysics - 在 PyByllet 中应用扭矩控制使物体飞离场景