Replacing selected with another text

前端 未结 2 931
我寻月下人不归
我寻月下人不归 2021-01-16 17:18

I am trying to replace selected text with another text.
Consider following is the line of text.

Hello world.Good morning. Hello world. Good mornin

2条回答
  •  误落风尘
    2021-01-16 17:39

    You could do it like this:

    SEE DEMO

    function swapSelection(swapText) {
      var sel = window.getSelection ? window.getSelection() : document.selection.createRange();
      if (sel != "") {
        if (sel.getRangeAt) {
          var range = sel.getRangeAt(0);
          var newNode = document.createElement("span");
          newNode.setAttribute('class', 'swapclass');
          range.surroundContents(newNode);
        } else {
          sel.pasteHTML('' + sel.htmlText + '');
    
        }
        $('.swapclass').replaceWith(swapText);
      }
    }
    
    $('button').click(function () {
      swapSelection('night');
    });
    

提交回复
热议问题