jQuery 无法在设计模式中捕获 keyup 目标元素

jQuery can't catch keyup target element in designmode

我正在尝试使用 jQuery 编写自己的所见即所得编辑器!

我需要捕获在编辑器框架上触发的事件。 "click" 事件工作正常并且具有正确的当前元素,但是 "keyup" returns 仅 <body> 在任何地方作为当前标签!我做错了什么?

<iframe id="editor"></iframe>
<script>

  // Define editor
  var editor = $('#editor').contents().find('body');

  // Switch to design mode
  $('#editor').contents().prop('designMode', 'on');

  editor.on("click", function(event) {
    console.log("clicked:" + event.target.nodeName + $(this).prop("tagName") + $(event.target).prop("tagName"));
  });

  editor.on("keyup", function(event) {
    console.log("key:" + event.target.nodeName + $(this).prop("tagName") + $(event.target).prop("tagName"));
  });

</script>

有例子:jsfiddle.net/p38L10zp/1

有两种检索当前正在编辑的元素的选项。

  1. 使用SelectionAPI确定目标HTML元素。
  2. 使用MutationObserver追踪<iframe>
  3. 内部的DOM突变

选择

请考虑第一种方法的工作示例JSFiddle

该示例很大程度上受到另一个 SO 问题的启发 Get parent element of caret in iframe design mode

MutationObserver

这个 API 的使用可能有些棘手,here's 一个非常具体的工作示例 use-case。

代码:

var editor = $('#editor').contents().find('body');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);

    if (mutation.type === 'characterData') {
        console.log('Tag name is: ' + mutation.target.parentNode.tagName);
    }
  });
});

// Configuration of the observer.
var config = {
  attributes: true,
  childList: true,
  characterData: true,
  subtree: true
};

observer.observe(editor[0], config);

$('#editor').contents().prop('designMode', 'on');

editor.append("<p>Test <b>bold</b> text</p>");