1. 在光标处插入 html
export const pasteHtmlAtCaret = (html) => {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
2. 在光标处插入内容
export const interposition = (id, text) => {
const contentEditableDiv = document.getElementById(id);
// 获取被选中的内容,起点和终点在同一位置为光标,不同位置为选区
const selection = window.getSelection();
// 被选中/focus的元素
const anchorNode = selection.anchorNode;
if (!anchorNode) return;
// 父节点
const parentNode = selection.anchorNode.parentNode;
const range = selection.getRangeAt(0);
let textNode = null
if (typeof (text) != 'string') {
textNode = text;
} else {
textNode = document.createTextNode(text);
}
if (anchorNode == contentEditableDiv
|| parentNode == contentEditableDiv) {
contentEditableDiv.insertBefore(textNode, nextText)
}
// collapse为true使起点和终点位于同一位置,即光标
// false时则为选区内容
range.collapse(true);
}
// 光标移到最后
const r = document.createRange();
r.selectNodeContents(textNode);
r.collapse(false);
const s = window.getSelection();
s.removeAllRanges();
s.addRange(r);
}