gpt4 book ai didi

javascript - jQuery 无法在设计模式下捕获 keyup 目标元素

转载 作者:行者123 更新时间:2023-12-01 01:42:45 25 4
gpt4 key购买 nike

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

我需要捕获在编辑器框架上触发的事件。 "click"事件工作正常并且具有正确的当前元素,但是 "keyup"仅返回 <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. 使用Selection用于确定目标 HTML 元素的 API。
  2. 使用MutationObserver跟踪 <iframe> 内的 DOM 突变

选择

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

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

突变观察者

此 API 的使用可能有些棘手,here's非常具体的用例的工作示例。

代码:

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>");

关于javascript - jQuery 无法在设计模式下捕获 keyup 目标元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com