Serializing html: placing span elements around sel

2019-09-12 04:56发布

问题:

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; }