js 在光标处插入内容

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值