Rya*_*ush 15 javascript-events tabindex google-chrome-extension autofocus
如何停止我的Google Chrome扩展程序的默认操作以自动关注我的第一个链接popup.html?我知道我可能会用JS做一些迂回的黑客攻击或改变:聚焦CSS,但我认为这会抛弃我想要做的其他事情,我宁愿停止它的根本原因.
Pau*_*ett 16
最简单的(和javascript免费!)方式是简单地添加tabindex="-1"到您不想接收自动焦点的任何元素.
也许自动对焦是为了方便起见,但通常会造成伤害.由于我认为无法阻止根本原因,我找到了一些环形交叉路口.一个是使用JavaScript.显示弹出窗口后,Chrome会在短暂延迟后自动对焦.它可能会使它失去焦点,blur()但是太过分散它太迟会使它瞬间闪现,并且过早地不聚焦也不会做任何事情.所以要找到合适的时间来解决这个问题并不容易,这个解决方案会在显示弹出窗口后的第一秒内尝试多次这样做:
document.addEventListener("DOMContentLoaded", function () {
var blurTimerId = window.setInterval(function() {
if (document.activeElement != document.body) {
document.activeElement.blur();
}
}, 200);
window.setTimeout(function() {
window.clearInterval(blurTimerId);
}, 1000);
});
Run Code Online (Sandbox Code Playgroud)
另一个纯HTML解决方案是将tabindex ="1"添加到body标签.
使用tabindex属性将最初关注的元素与属性进行整理可能是最好的方法:
tabindex="-1",如Paul Ferret所建议的那样,以防止某个元素获得焦点tabindex="1",如link0ff所建议,以指定哪个元素应以focus开头如果您的情况更为复杂,并且您确实希望引入一些JavaScript,我建议您使用link0ff的解决方案,除了不要尝试猜测何时会因超时而模糊,还应监听事件的初始焦点:
function onInitialFocus(event) {
// Any custom behavior your want to perform when the initial element is focused.
// For example: If this is an anchor tag, remove focus
if (event.target.tagName == "A") {
event.target.blur();
}
// ALSO, remove this event listener after it is triggered,
// so it's not applied to subsequent focus events
document.removeEventListener("focusin", onInitialFocus);
}
// NOTE: the "focusin" event bubbles up to the document,
// but the "focus" event does not.
document.addEventListener("focusin", onInitialFocus);
Run Code Online (Sandbox Code Playgroud)
我不认为焦点事件是可以取消的,因此您不能仅仅取消该事件。
| 归档时间: |
|
| 查看次数: |
2380 次 |
| 最近记录: |