首页 > 解决方案 > 无法使用 FireFox 中的事件对象访问 relatedTarget

问题描述

我正在CodeMirror为 YAML 使用编辑器。我有下面的代码。

$('#' + element.id).ready(function() {
  editor = CodeMirror.fromTextArea(document.getElementById(element.id), Options);
  editor.setValue(self.test());
  editor.on('blur', function(event) {
    var clickedElement = event.relatedTarget;
    var isAddDialogButtonClicked = false;
    if (clickedElement !== null) {
      isAddDialogButtonClicked = clickedElement && clickedElement.parentElement &&
        clickedElement.parentElement.id === bindingContextData.addDialogButtonId();
    }
  });
});

event.relatedTargetFireFox 中不起作用。它在 Chrome 中运行良好。关于如何解决这个问题的任何想法?

标签: jqueryeventscodemirror

解决方案


您可以使用 jQuerys 事件访问本机 DOM event.originalEvent,也许您可​​以在其中找到相关的目标?同样根据MDNevent.relatedTarget仅适用于某些事件。复制自 MDN 2018-12-07:

The MouseEvent.relatedTarget read-only property is the secondary target for the mouse event, if there is one.

Event name     target                                           relatedTarget
focusin        The EventTarget receiving focus                  The EventTarget losing focus
focusout       The EventTarget losing focus                     The EventTarget receiving focus
mouseenter     The EventTarget the pointing device entered to   The EventTarget the pointing device exited from
mouseleave     The EventTarget the pointing device exited from  The EventTarget the pointing device entered to
mouseout       The EventTarget the pointing device exited from  The EventTarget the pointing device entered to
mouseover      The EventTarget the pointing device entered to   The EventTarget the pointing device exited from
dragenter      The EventTarget the pointing device entered to   The EventTarget the pointing device exited from
dragexit       The EventTarget the pointing device exited from  The EventTarget the pointing device entered to

For events with no secondary target, relatedTarget returns null.

blur在那里没有,但我很确定blur它只是focusout.

或者,直接挂钩到 vanilla javascript,jQuery 被高估了:

editor[0].addEventListener( 'blur', function( event ){
    // whatevs
}

editor[0]从返回的 jQuery 对象访问本机 DOM 元素)

否则,重构?


推荐阅读