围绕 DIV 中的选定文本动态创建 SPAN

Sri*_*nan 2 html javascript css jquery

我的 HTML 页面中有一个 div,如下所示:

    <div class="well editor" id="highlighted-text" 
style="overflow: scroll; overflow-x:hidden;height:500px;" contenteditable></div>
Run Code Online (Sandbox Code Playgroud)

当我选择 div 中的一部分文本并单击按钮时,我想突出显示所选文本。

我知道这可以通过在所选文本周围添加带有类选择器的跨度来完成,但我无法围绕所选文本创建跨度:

var node = window.getSelection().focusNode;
$(node).wrapInner("<b></b>");
Run Code Online (Sandbox Code Playgroud)

这不起作用。感谢您的帮助。提前致谢。

Sri*_*nan 6

我明白了......我这样做了:

var selection= window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span= document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selectedText);
selection.insertNode(span);
Run Code Online (Sandbox Code Playgroud)