Serializing html: placing span elements around selected text while preserving the HTML structure

心不动则不痛 提交于 2019-12-12 04:19:53

问题


I am trying to make a text highlighter where a teacher can select a range of text so that the student can follow along. The text is formatted with HTML so there are <p>, <b>, <em> etc... elements.

To highlight the range of text I am wrapping the range in a span element.

The issue:

https://jsfiddle.net/7fedkobr/1/

Here is a sentence with some HTML markup:

<p>The <b>quick</b> brown fox jumps over the <em>lazy</em> dog</p>

When I select a word such as 'The' it gets wrapped in a <span>, boom, no problem.

The issues come when I try and select over any html tags... for example if I select the entire sentence then I lose ALL my mark-up.

What I am looking for.

A method to serialize the spans so that they fall in-between the html elements and wrap all the text.

Using the previous example: if I select the entire sentence above then I would get the following output:

<p><span>The </span><b><span>quick</span></b><span> brown fox jumps over the </span><em><span>lazy</span></em><span> dog</span></p>

Q:

Is there a method for this kind of serialization? I can't find anything in the jQuery docs and the few people I have asked were stumped.


回答1:


The key is to use range.extractContents(). The documentation states the most important part for your needs:

Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.

document.getElementById('test').addEventListener('mouseup', function() {
    var range = window.getSelection().getRangeAt(0),
        span = document.createElement('span');

    span.className = 'highlight';
    span.appendChild(range.extractContents());
    range.insertNode(span);
});
.highlight { background-color: yellow; }
<div id="test">
    Select any part of <b>this sentence and</b> and then move the mouse to a new location.
</div>

You can see in the picture below that the resulting HTML from a selection does exactly what you are asking:




回答2:


I don't think you need jquery for that, plain CSS will do the trick:

*::selection { background-color: yellow !important; }


来源:https://stackoverflow.com/questions/42656501/serializing-html-placing-span-elements-around-selected-text-while-preserving-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!