当iframe主体的设计模式处于打开状态时,如果我们按Enter键,则div会附加到文档主体中,如下所示:
<body>
<div><br/></div>
</body>
这对我的用例来说非常有用,因为我正在使用文本编辑器来支持代码块和blockquote以及粗体,斜体,下划线。
我应用Blockquote和CodeBlock的方法是定义了CSS,并将类添加到相应的div / code元素
为了将这些类应用于div,我需要知道我的插入符号到底在哪里。因此,例如,我在正文中并为blockquote添加了一些文本,那么我怎么知道在哪个子元素(div)处保持要格式化的文本。
var editor=document.getElementById("rtfiframe").contentWindow.document.body;
editor.document.designMode = 'On';
var editor=document.getElementById("rtfiframe").contentWindow.document.body;
我通过单击来尝试,每当我单击编辑器时,我都可以得到被点击孩子的位置:-
var currentLineClicked;
function setIndexOfClicked() {
for (var i = 0, len = editor.children.length; i < len; i++)
{
(function(index){
editor.children[i].onclick = function(){
// alert(index) ;
currentLineClicked =index;
console.log("clicked div index is :"+currentLineClicked);
}
})(i);
}
}
之后,我可以成功地向该div添加一个类:
function applyBlockquote(){
var currentIndex = currentLineClicked;
console.log(editor.children[currentIndex]);
editor.children[currentIndex].className = "bquote";
}
但是,如果用户通过按Enter键在体内添加了一些额外的孩子呢?我尝试使用MutationObserver来检测节点中正在执行哪种更改,但是找不到如何获取插入符/光标的当前位置?
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
与我的想法非常接近的参考/示例是 Markdown Editor :
我可以看到此处正在使用隐藏的文本区域。(Image of Inspected Element)