When we need the mouse to select the text, the text is highlighted. What happens when the highlight is unhighlighted after the selected text is selected again?

Window. GetSelection

To get the mouse-selected content, we use the window.getSelection() API. Returns a Selection object that represents the range of text or the current position of the cursor selected by the user.

Selection objects correspond to the ranges selected by the user, commonly known as drag blue. By default, this function is for only one region. We can use this function like this:

var selObj = window.getSelection(); var range = selObj.getRangeAt(0); // selObj is assigned a Selection object // range is assigned a range objectCopy the code

Calling the selection.toString () method returns plain text in the selected region. Functions that require strings do this automatically for objects, for example:

var selObj = window.getSelection();
window.alert(selObj); 
Copy the code

Some introduction to Range can be seen in this article by Zhang Xinxu: JS Range HTML document/text selection, library and application introduction

Second, some existing third-party libraries

  1. web-highlighter

This is a very good “underline word highlighting” function to achieve third party library, direct reference can be, simple implementation. Refer to the article can see how to use JS to achieve “underline word” online notes function

Specific use:

Install NPM I web-highlighter // use import highlighter from'web-highlighter';
(new Highlighter()).run();
Copy the code

Highlighted region persistence:

import Highlighter from 'web-highlighter'; // 1. Instantiate const highlighter = new highlighter (); // 2. Get the highlight information from the backend (getRemoteData), Restore to getRemoteData().then(s => highlighter. FromStore (s.startMeta, s.endmeta, s.id, s.ext)); / / 3. The highlighted notes CREATE event monitoring, and save the information to the back-end highlighter. On (highlighter. Event. The CREATE, ({sources}) = > save (sources)); // 4. Enable automatic stroking highlighter. Run ();Copy the code

The sources obtained by the listener note creation event in persistence is an array, and the array elements are objects, as shown in the following figure:

// contains startMeta, endMeta, text, and id [{startMeta: {parentTagName:"A", parentIndex: 6, textOffset: 2}
    endMeta: {parentTagName: "H2", parentIndex: 0, textOffset: 2}
    text: "Chinese ↵ Ba"
    id: "91031887-238c-4118-a5b7-9def992b9479"
}]
Copy the code

  1. Analyze uEditor and replication

Refer to this article to add styles and annotations to the selected text with JS, then grab the uEditor source code on GitHub two or three times and start reading the source code to analyze the code. After removing some unnecessary code and compatibility, I got five files:

  • Browser.js (browser version judgment, for compatibility processing)
  • Domutils.js (DOM manipulation)
  • Dtd.js (Node type and element judgment)
  • Range.js (encapsulated selected Range objects)
  • Utils.js (utility class)

The original author code demo address, the part used below is slightly different from that of the blogger.

Main code used:

import Range from "./utils/Range";
import domUtils from "./utils/domUtils.js";

const getSelectText = () => {
    var getRange = () => {
        var me = window;
        var range = new Range(me.document);

        var sel = window.getSelection();
        if (sel && sel.rangeCount) {
            var firstRange = sel.getRangeAt(0);
            var lastRange = sel.getRangeAt(sel.rangeCount - 1);
            range.setStart(firstRange.startContainer, firstRange.startOffset)
                .setEnd(lastRange.endContainer, lastRange.endOffset);
        }
        returnRange} // If you select a class whose parent contains a red color, remove the span tag with a red color; otherwise, add the SPAN tag for selectionif (domUtils.hasClass(range.startContainer.parentNode, "red-color")) {
        range.removeInlineStyle("span"."red-color");
    } else {
        range.applyInlineStyle("span", {
            class: "red-color"}); range.select(); }}; <div onMouseUp={getSelectText} dangerouslySetInnerHTML={{__html: 'haw haw haw, Mulan when the door weaved. Hear not the sound of the loom, but the sigh of the woman. <br> Ask a woman what she thinks and what she remembers. Women have no thoughts, women have no memory. Last night saw the army post, Khan big point soldiers, army book twelve volumes, volumes have ye name. Ye no big son, magnolia no elder brother, is willing to saddle horse for the city, from now on for ye zheng. ` }} > </div>Copy the code

See the code demo address above

Iii. Other relevant content

  1. In the range of::selectionThe selector

The :: Selection selector can be used to create a uniform style for the site.

:: Selection CSS pseudo-elements apply to portions of the document that are highlighted by the user (such as portions selected using a mouse or other selection device).

::selection {
  background-color: cyan;
}
Copy the code

Below is a DEMO GIF of MDN:

This is a summary of the highlight effect on the selected text.

References:

  1. Window. The MDN 】 【 getSelection ()
  2. 【 MDN 】 Selection
  3. 【 MDN 】 ranges
  4. JS Range HTML document/text content selection, library and application introduction
  5. web-highlighter
  6. How to use JS to realize the online note-taking function of “underline word”
  7. Add styles and annotations to the selected text with JS
  8. JavaScript standard Selection operation
  9. 【 MDN 】 : : selection