我试图用jQuery编写自己的WYSIWYG编辑器!
我需要捕捉在编辑器框架中触发的事件。 "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>
答案 0 :(得分:0)
有两种方法可以检索当前正在编辑的元素。
<iframe>
请在此 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>");