如何在 Javascript 中创建 "about To Blur" 或 "will blur" 事件?

How to create an "about To Blur" or "will blur" event in Javascript?

我有一些代码 运行s 在元素的 "blur" 事件上。 此代码需要实际使用 activeElement,因此实际上不能 运行 来自 "blur" 事件。

我希望我能举办这样的活动。目的是 "willblur" 事件将在 "blur" 事件之前触发。

  var lastTouchedElement;

  $('body').on('click', preBlurHandler);
  $('body').on('focusin', postFocusHandler);
  $('.inp1').on('willblur', function() {alert('willblur');});
  $('.inp1').on('blur', function() {alert('blur');});


  function preBlurHandler(ev) {

    if (!lastTouchedElement) {
      postFocusHandler(ev);
      return;
    }

    var focussingElement = ev.target;

    if (lastTouchedElement === focussingElement || $.contains(lastTouchedElement, focussingElement)) {
      //focus is staying in the same place, do nothing
      return;
    }

    $(lastTouchedElement).trigger('willblur', [ev, {
      target: lastTouchedElement,
      focussingElement: focussingElement
    }]);
  }


  function postFocusHandler(ev) {
    lastTouchedElement = document.activeElement; 
  }

完整代码位于 https://jsfiddle.net/t0un95jt/3/

的 JSFiddle 中

但是没用。事实上,它甚至还差得远。

帮助我 Whosebug;你是我唯一的希望。

关键是使用 addEventListener 而不是 JQuery 的 on(),并使用 "mousedown" 而不是 "click"。

代替这一行:

$('body').on('click', preBlurHandler);

我用这个:

window.addEventListener('mousedown', preBlurHandler, true);

addEventListener 的最后一个参数:true,表示 "do this on the capturing phase"。捕获阶段从最外层元素开始,并通过在后续子元素上触发事件来工作,在冒泡阶段开始之前,它返回 DOM 树。