参考 https://developer.mozilla.org/zh-CN/docs/Web/API/Range/surroundContents
window.getSelection() 等价于 document.getSelection
返回一个 Selection 对象,表示用户选择的文本范围或光标的当前位置。
const selection = window.getSelection();
selection.toString(); //用于获取当前选中文本的文字
Range对象
Range接口表示一个包含节点与文本节点的一部分的文档片段。
const range = window.getSelection().getRangeAt(0);
const docObj = range.extractContents(); //移动了Range 中的内容从文档树到DocumentFragment(文档片段对象)。
let dom = document.createElement(‘span’);
dom.style.color = ‘red’;
dom.appendChild(docObj);
range.insertNode(dom);