InvalidStateError:无法在“范围”上执行“surroundContents”:范围已部分选择非文本节点

Md *_*rim 7 javascript reactjs

美好的一天,我正在尝试制作一个阅读器,用户可以通过多种颜色突出显示文本,我在下面的沙箱链接上编写了代码。

https://codesandbox.io/s/gallant-snowflake-oxko7?file=/src/App.js

一切工作正常,但是当我尝试通过选择选定的文本更改先前突出显示的颜色时,我收到此错误。

InvalidStateError:无法在“范围”上执行“surroundContents”:范围已部分选择非文本节点。 在此输入图像描述

Md *_*rim 14

我找到了一些解决方案并通过它修复了它。下方链接

更改了代码

let span = document.createElement("span");

    t = document.all
      ? document.selection.createRange().text
      : document.getSelection();
    setXaxis(e.clientX / 2);
    setYaxis(e.clientY / 2);

    console.log(e.clientX);
    console.log(e.clientY);
    // let text =  document.querySelector(".App").innerText;
    //document.querySelector(".App").html(text.replace(t, spn));
    //document.getElementById('result').innerText = t;
    //alert(t.rangeCount);
    span.style.backgroundColor = color;
    let range = t.getRangeAt(0).cloneRange();
    range.surroundContents(span);
    t.removeAllRanges();
    t.addRange(range);
Run Code Online (Sandbox Code Playgroud)

 var range = window.getSelection().getRangeAt(0);
let span = document.createElement("span");

span.style.backgroundColor = color;
span.appendChild(range.extractContents());
range.insertNode(span);
Run Code Online (Sandbox Code Playgroud)

https://codesandbox.io/s/optimistic-https-zlfpe?file=/src/App.js