哪种方法更正确地获取文档中具有焦点的元素?

发布于 2024-08-18 10:47:18 字数 396 浏览 2 评论 0原文

我已经询问了几个与此相关的问题,并且发现了两种常见的方法。

  1. 拥有全局元素,并通过将 onFocus() 事件附加到每个元素来更新它。
  2. document.activeElement 并使用以下代码来更新元素,以防旧浏览器不支持该属性

    var focusElement;
    document.addEventListener("焦点", 函数(e) {
        focusElement = e.target;
    }, 真的);
    document.addEventListener("模糊", 函数(e) {
        焦点元素 = null;
    }, 真的);
    

现在我的问题是上述两种方法中哪一种更正确/简单/高效?为什么? 谢谢大家,

I have went through couple of questions already asked related with this and i have found two common approach.

  1. Have global element and update it by attaching onFocus() event to each of the element.
  2. document.activeElement and have following code to update the element in case of old browser which do not support the property

    var focusedElement;
    document.addEventListener("focus", function(e) {
        focusedElement = e.target;
    }, true);
    document.addEventListener("blur", function(e) {
        focusedElement = null;
    }, true);
    

Now my question is which one is more correct/easy/efficient approach of above two? why?
Thanks all,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雾里花 2024-08-25 10:47:18

你的解决方案1效率非常低。当您可以附加到主体本身时,将事件处理程序附加到页面上的每个(可聚焦)元素?这肯定不是正确/简单/有效的方法。解决方案2看起来很不错。

Your solution 1 is horribly inefficient. Attaching an event handler to each and every (focusable) element on the page when you could attach to the body itself? That is not the correct/easy/efficient way to do it for sure. Solution 2 looks pretty good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文