如何判断焦点去哪里了?

发布于 2024-11-30 05:30:31 字数 359 浏览 5 评论 0原文

此处已提出此问题< /a> 之前,但是是几年前的事了,当时还没有跨平台的解决方案(除了 setTimeout 解决方案,这确实不是很方便)。

我想做 onblur="foo(parm);" 并让 foo 能够确定哪个元素现在具有焦点。

我正在使用常规的 javascript;请不要使用 jQuery。

如今这可能吗?

This has been asked here before, but several years ago, and there was no cross-platform solution at the time (other than the setTimeout solution, which is really not very handy).

I'd like to do onblur="foo(parm);" and have foo be able to determine which element now has focus.

I'm using regular javascript; no jQuery for this one, please.

Is that possible these days?

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

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

发布评论

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

评论(5

忆梦 2024-12-07 05:30:32

你可以尝试这样的事情:

function whereDidYouGo() {
    var all = document.getElementsByTagName('*');

        for (var i = 0; i < all.length; i++)
            if (all[i] === all[i].ownerDocument.activeElement)
                return all[i];
}

编辑:

function whereDidYouGo() { return document.activeElement; }

You can try something like this:

function whereDidYouGo() {
    var all = document.getElementsByTagName('*');

        for (var i = 0; i < all.length; i++)
            if (all[i] === all[i].ownerDocument.activeElement)
                return all[i];
}

EDIT:

function whereDidYouGo() { return document.activeElement; }
勿忘初心 2024-12-07 05:30:32

在 jQuery 中,应 OP 的要求:

$(':input').blur(function() {
    $focusedElement = $(':input:focus');
    //Do stuff with $focusedElement
}

In jQuery, at the OP's request:

$(':input').blur(function() {
    $focusedElement = $(':input:focus');
    //Do stuff with $focusedElement
}
暮色兮凉城 2024-12-07 05:30:32

有趣的问题。问题的核心是 - “焦点”事件何时触发,在模糊事件之前还是之后?如果它在模糊事件之前触发,问题很容易,因为您只需将当前焦点存储在模糊事件可以访问的变量中。

然而,至少在 Chrome 13 中,模糊事件似乎发生在焦点事件之前。一种可能的解决方案。

给定以下 HTML:

<input id="foo" value='foo' />
<input id="bar" value='bar' />

然后您可以:

var currentFocus;
var pendingBlur;

var foo = document.getElementById('foo');
foo.addEventListener('focus', function(){ 
    currentFocus = foo;
    if(pendingBlur !== undefined){
        pendingBlur();
        pendingBlur = undefined;
    }
});
foo.addEventListener('blur', function(){
    pendingBlur = function(){
        console.log('new focus:', currentFocus);
    };
});

var bar= document.getElementById('bar');
bar.addEventListener('focus', function(){ 
   currentFocus = bar;
   if(pendingBlur !== undefined){
        pendingBlur();
        pendingBlur = undefined;
   }
});
bar.addEventListener('blur', function(){
    pendingBlur = function(){
        console.log('new focus:', currentFocus);
    };
});

基本上,我只是不执行模糊回调,因此在我们知道哪个元素获得焦点后调用焦点事件会很方便。

这是 JSFiddle 上的工作示例

编辑:此解决方案存在这样的问题:如果您通过单击其他表单元素之外的其他内容来模糊表单,则模糊事件永远不会触发(因为我们等待焦点事件)。我能想到的唯一解决方法是使用计时器来检查是否定义了pendingBlur,如果是,则调用它。此时您实际上不再需要焦点事件来调用模糊回调......

Interesting question. The heart of the matter is - when does the 'focus' event fire, before or after the blur event? If it fires before the blur event, the problem is easy, because you can just store the current focus in a variable that your blur event can access.

However, at least in Chrome 13, it appears the blur event happens before the focus event. One possible solution.

Given the following HTML:

<input id="foo" value='foo' />
<input id="bar" value='bar' />

You can then:

var currentFocus;
var pendingBlur;

var foo = document.getElementById('foo');
foo.addEventListener('focus', function(){ 
    currentFocus = foo;
    if(pendingBlur !== undefined){
        pendingBlur();
        pendingBlur = undefined;
    }
});
foo.addEventListener('blur', function(){
    pendingBlur = function(){
        console.log('new focus:', currentFocus);
    };
});

var bar= document.getElementById('bar');
bar.addEventListener('focus', function(){ 
   currentFocus = bar;
   if(pendingBlur !== undefined){
        pendingBlur();
        pendingBlur = undefined;
   }
});
bar.addEventListener('blur', function(){
    pendingBlur = function(){
        console.log('new focus:', currentFocus);
    };
});

Basically, I just not the blur callback so it is handy for the focus event to call after we know about which element was focused.

Here is a working example on JSFiddle.

EDIT: This solution suffers from the problem that if you blur on the form by clicking on something other than another form element, the blur event never fires (since we wait for the focus event). The only way around that, that I can conceive, is using a timer to check if pendingBlur is defined, and if so, call it. At which point you don't really need the focus event to call the blur callback anymore...

风情万种。 2024-12-07 05:30:32

2020 年:所有主要浏览器(桌面版和移动版)均支持 FocusEvent。相关目标

Year 2020: All major browsers (desktop and mobile) support FocusEvent.relatedTarget.

得不到的就毁灭 2024-12-07 05:30:32

event.latedTarget 找不到新聚焦的元素(在我的例子中是 div 类型),但只返回 null

在元素上附加属性 tabindex="0" 后,现在它可以工作了。

<div id="myDiv">myDiv</div>
console.log(e.relatedTarget) // null

<div id="myDiv" tabindex="0"> tabindexed div </div>
console.log(e.relatedTarget) // <div id="myDiv" tabindex="0">

tabindex 是一个使元素可以使用键盘上的 Tab 键获得焦点的属性。我想这主要是为了网络可访问性。

我猜你不需要设置 tabindex 属性,只要焦点元素已经可以通过 Tab 键访问(例如 aselect< /代码>..等等)

event.relatedTarget couldn't find the newly-focused element(was div type in my case), but only null gets returned.

After attaching the attribute tabindex="0" on the element, now it works.

<div id="myDiv">myDiv</div>
console.log(e.relatedTarget) // null

<div id="myDiv" tabindex="0"> tabindexed div </div>
console.log(e.relatedTarget) // <div id="myDiv" tabindex="0">

tabindex is an attribute that make elements focusable using tab key on keyboard. I guess it is mainly for web accessibility.

And I guess you won't need to set tabindex attribute as long as to-be focused elements are already accessible by tab key (such as a, select.. and so on)

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