获取触发jquery blur()事件的单击对象

pil*_*ght 41 javascript jquery events javascript-events onblur

假设我这样做:

$(target).blur(function(e){
  //do stuff
});
Run Code Online (Sandbox Code Playgroud)

有没有办法获取被点击的对象以触发模糊操作?

我尝试使用e.target,但这似乎是返回附加到模糊操作的对象而不是单击的对象.

blo*_*ead 46

诀窍是等待一个额外的滴答:

$(el).blur(function (event) {
    // If we just hangout an extra tick, we'll find out which element got focus really
    setTimeout(function(){
       document.activeElement; // This is the element that has focus
    },1);
})
Run Code Online (Sandbox Code Playgroud)

  • 我发现`setTimeout`需要一个明确的延迟来允许其他`click`事件触发; 也为我(jQuery 1.8)`document.activeElement`是`body`,这不是很有帮助:) (2认同)
  • 我应该补充一点,通过使用“setImmediate”或“requestAnimationFrame”,可能有更好的方法来做到这一点,所有这些都是相同的 (2认同)

dar*_*ryl 37

如果我理解你的问题,应该这样做:

$(function() {

    var clicky;

    $(document).mousedown(function(e) {
        // The latest element clicked
        clicky = $(e.target);
    });

    // when 'clicky == null' on blur, we know it was not caused by a click
    // but maybe by pressing the tab key
    $(document).mouseup(function(e) {
        clicky = null;
    });

    $(target).blur(function(e) {
        console.log(clicky);
    });??

});
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 7

在事件处理程序内部,this将是事件绑定的元素,并且e.target将是触发事件的元素(可能与否相同this).

你正在处理一个blur事件,而不是一个click事件.因此,在您的活动中,您将拥有您blur编辑的元素.如果你想要clicked元素,你需要另一个事件来获得它.

blur可以由其他事件触发,例如聚焦某事; 不只是点击某事.所以,没有办法让元素"引起模糊".

  • 在Flash / AS3中,通过FocusIn和FocusOut事件很容易实现这一点,其中包括接收和失去焦点的对象以及简单的取消功能。很高兴看到在2018年,JavaScript / HTML落后Flash超过十年了,没有简单的方法可以做到这一点。我讨厌这样发表评论,但是AS3语言相对于JS的绝对优势变得越来越令人烦恼,因为我看到JS一年又一年地保持可怕和缺乏。 (2认同)