问题描述
我使用 editableContent div 作为各种文本编辑器。
这个 html 元素 <div id="content" class='print-content' media = "print" contenteditable="true"> </div>
充当其他元素的父节点。问题在于,每次将新元素附加到该父元素时,文本插入符号都会移回第一个插入的节点。我想知道是否有办法防止这种情况发生。
根据用户触发的键绑定或按钮,将创建一个新元素,然后根据当前选定元素在父 childrenNode 数组中的位置插入。整个过程在下一个片段中描述:
function newElement(type) {
console.log("Current counter: ",counter);
counter = counter + 1;
id = counter.toString();
getId = "currentElemIndex(" + id + ")";
let newElement = document.createElement("P");
newElement.setAttribute('class',type);
newElement.setAttribute('id',id);
//newElement.setAttribute('tabindex',1);
newElement.setAttribute('data-placeholder',type)
newElement.setAttribute('contentEditable','true');
newElement.setAttribute("onclick",getId);
if (type == 'parenthesis') {
newElement.innerText = '()';
};
insertElement(newElement,id);
};
function insertElement(newElement,id) {
let nodes = Array.from(content.childNodes);
if (currentIndex + 1 == content.childNodes.length) {
//content.appendChild(newElement);
content.append(newElement);
} else {
console.log('Current Index from insert element: ',currentIndex);
nodes.splice(currentIndex + 1,newElement);
renderElements(nodes,newElement);
}
if (currentIndex != 0) {
currentIndex += currentIndex + 1;
}
};
function renderElements(arr,newElement) {
content.innerHTML = "";
arr.forEach(dialog => {
content.innerHTML += dialog.outerHTML;
});
};
每次通过此函数附加新元素时,文本插入符都会跳回数组中的第一个元素,而不是将自身锁定在新创建和附加的元素中。
我还在 enter 键上使用了 e.preventDefautl 方法,因为它只是创建了前一个元素的副本并将其附加到当前所选元素的下方。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)