开发者

replace selected text in contenteditable div

I have been looking high and low for an answer but failed.

Is there a cross-browser solution to replace selected text in cont开发者_如何学JAVAenteditable div?

I simply want users to highlight some text and replace the highlighted text with xxxxx.


The following will do the job in all the major browsers:

function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = replacementText;
    }
}


As I posted a working example on how to add emoji in between the letters in contentEditable div? , you can use this for replacing the needed text in content editable div

  function pasteHtmlAtCaret(html) {
        let sel, range;
        if (window.getSelection) {
          // IE9 and non-IE
          sel = window.getSelection();
          if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            const el = document.createElement("div");
            el.innerHTML = html;
            let 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);
        }
      }

      function addToDiv(event) {
        const emoji = event.target.value;
        const chatBox = document.getElementById("chatbox");
        chatBox.focus();
        pasteHtmlAtCaret(`<b>${emoji}</b>`);
      }
      function generateEmojiIcon(emoji) {
        const input = document.createElement("input");
        input.type = "button";
        input.value = emoji;
        input.innerText = emoji;
        input.addEventListener("click", addToDiv);
        return input;
      }
      const emojis = [
        {
          emoji: "
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜