15

In some business scenarios, such as highlighting text, inputting and editing, etc., when you need to manipulate the cursor and the selection, you can use the Selection and Range objects provided by the browser to operate the cursor and the selection.

Selection object

Selection object represents the current position of the selection or caret selected by the user, and it may span multiple elements.

//获取 Selection 对象
window.getSelection();

The user may select text from left to right (same direction as the document) or from right to left (opposite to the document direction).

anchor (anchor): refers to the place where the user starts to select.
focus (focus): refers to the place where the user ends the selection.

If you use the mouse to select text, anchor refers to the place where you press the mouse button, and focus refers to the place where you release the mouse button. anchor and focus concepts can not be confused with the selection of the starting position and end position, because anchor may focus front, may also be in focus back, depending on the direction you move the mouse to select text, which is the mouse button is pressed And release the mouse button.

As shown below:

Attributes:

  • anchorNode: The anchor point ( anchor ) is located.
  • anchorOffset:

    • If anchorNode is a text node or a comment node, return the anchor ) to the first word in the node.
    • If anchorNode is an element node, return the total number of sibling nodes before the anchor
  • focusNode: focus focus ).
  • focusOffset:

    • If focusNode is a text node or a comment node, return the focus ( focus ) to the number of characters in the first word in the node.
    • If focusNode is an element node, return the total number of nodes at the same level before the focus
  • isCollapsed: Boolean value indicating whether the start position and end position of the selection overlap. If it is true , it can be considered that there is no content currently selected.
  • rangeCount: constituency included Range number of objects.
  • type: describes the type of the current selection, with the following three values:

    • None: currently not selected.
    • Caret: only click, but not selected, the selection is collapsed (that is, the cursor is between the characters, not in the selected state).
    • Range: selects a range.

Note:
All the above attributes are read-only attributes .

method:

  • addRange(range)

    The selection ( Selection to add a region (object) in Range object).

    parameter:

    range : an area object

    Example:

    <p id="text">文本</p>
    //添加一个选区
    var text = document.querySelector("#text");
    var selObj = window.getSelection();
    var rangeObj = document.createRange();
    rangeObj.selectNode(text);
    selObj.addRange(rangeObj);
  • collapse(parentNode,offset)

    Collapse the current selection to a point. The document will not change.

    parameter:

    parentNode : The target node where the cursor falls
    offset : optional, the offset within the target node

    Example:

    <div contenteditable="true" id="text">文本</div>
    //收起选区到一个点,光标落在一个可编辑元素上
    var text = document.querySelector("#text")
    window.getSelection().collapse(text,0);
  • collapseToEnd()

    Cancel the current selection and position the cursor at the end of the original selection.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    selObj.collapseToEnd();
  • collapseToStart()

    Cancel the current selection and position the cursor at the beginning of the original selection.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    selObj.collapseToStart();
  • containsNode(aNode,aPartlyContained)

    Determine whether the specified node is included in the Selection object (that is, whether it is selected).

    parameter:

    aNode : Used to determine whether the node Selection
    aPartlyContained
    When this parameter is true time, Selection object contains aNode part or all of the time, containsNode() method returns true .
    When this parameter is false (default value), only when the Selection object completely contains aNode , the containsNode() method returns true .

    Example:

    <div id="text">文本</div>
    var text = document.querySelector("#text");
    var selObj = window.getSelection();
    var contains = selObj.containsNode(text);
  • deleteFromDocument()

    Delete the selected document fragment from DOM

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    selObj.deleteFromDocument();
  • extend(node,offset)

    Move the focus of the selection ( focus ) to the specified point. The anchor point of the selection ( anchor ) will not move. The selection will start from the anchor point ( anchor ) to the new focus point ( focus ), regardless of direction.

    parameter:

    node : The focus ( focus ) will be moved to this node.
    offset : Optional, the default value is 0, the focus ( focus ) will be moved to the offset position within node

    Example:

    <div id="text">文本</div>
    var text = document.querySelector("#text");
    var selObj = window.getSelection();
    selObj.extend(text);
  • getRangeAt(index)

    Range object contained in the current selection.

    parameter:

    index : This parameter specifies the index of the Range If the value is greater than or equal to rangeCount , an error will be reported.

    Example:

    //获取一个 Selection 对象
    var selObj = window.getSelection();
    //获取一个 Range 对象
    var rangeObj  = selObj.getRangeAt(0);
  • modify(alter,direction,granularity)

    Use text commands to change the current selection or cursor position.

    parameter:

    alter : To change the type, pass in move to move the cursor position, or extend to expand the current selection.
    direction : Adjust the direction of the selection. You can pass in forward or backward to adjust according to the language writing direction of the selection. Or use left or right to indicate a clear adjustment direction.
    granularity : Adjusted distance granularity. Optional values are character , word , sentence , line , paragraph , lineboundary , sentenceboundary , paragraphboundary , documentboundary .

    Example:

    var selection = window.getSelection();
    selection.modify("extend", "forward", "word");
  • removeAllRanges()

    Will remove all Range objects from the current Selection object and cancel all selections.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    selObj.removeAllRanges();
  • removeRange(range)

    Remove a Range object from the selection.

    parameter:

    range Range object that will be removed from the selection.

    Example:

    var selObj = window.getSelection();
    var rangeObj = selObj.getRangeAt(0)
    selObj.removeRange(rangeObj);
  • selectAllChildren(parentNode)

    Set all child elements of the specified element as a selection (except the element itself), and cancel the previous selection.

    parameter:

    parentNode : Specify the element

    Example:

    <div id="selectAll">
      <div>文本1</div>
      <div>文本2</div>
    </div>
    var selectAll = document.querySelector("#selectAll");
    var selObj = window.getSelection();
    selObj.selectAllChildren(selectAll);
  • setBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset)

    Select the content between two specific DOM

    parameter:

    anchorNode : the starting node of the selected content
    anchorOffset : The offset of the starting position of the anchorNode
    If anchorNode is a text node, it means that the starting position of the selection is in the character position of the node.
    If anchorNode is an element node, it means that the starting position of the selection is in the position of the child node of the node.
    focusNode : the end node of the selected content
    focusOffset : The offset of the end position of the focusNode
    If focusNode is a text node, it means the end position of the selection is in the character position of the node.
    If focusNode is an element node, it means that the selection ending position is the position of the child node in the node.

Example:

<div id="start"></div>
<div id="end"></div>
var start = document.querySelector("#start");
var end = document.querySelector("#end");
var selObj = window.getSelection();
selObj.setBaseAndExtent(start,0,end,0);
  • toString()

    Returns the string representing the current Selection object, such as the currently selected text.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    selObj.toString();

Range object

Range object represents the selected document fragment. A Range object may contain the entire element node or part of the element node, such as part of the text of the text node. The user usually can only select one Range object, but sometimes the user may also select multiple Range objects (only Firefox can select multiple Range objects).

You can use Document.createRange method of the Document object to Range , or you can use getRangeAt method of the Selection object to Range . Further, by the Document object constructor the Range () obtained Range .

Attributes:

  • collapsed: returns a value Boolean that indicates whether the start position and the end position are the same.
  • commonAncestorContainer: returns the deepest node startContainer and endContainer
  • endContainer: returns the node containing the end position of Range
  • endOffset:

    • If endContainer is a text node or a comment node, the number of characters from the first word of the node to the boundary of the selection area (that is, the number of characters selected) is returned.
    • If endContainer is an element node, return the total number of nodes at the same level before the first node after the end position of the selection.
  • startContainer: returns the node containing the start position of Range
  • startOffset:

    • If startContainer is a text node or a comment node, return the number of characters from the first word of the node to the boundary of the selection area (that is, the number of characters that are not selected).
    • If startContainer is an element node, return the total number of nodes at the same level before the first node at the beginning of the selection.

Note:
All the above attributes are read-only attributes .

method:

  • cloneContents()

    Return a document fragment, which is a copy of all nodes in the Range

    parameter:

    no

    Example:

    // 在文档中插入选中元素
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    documentFragment = rangeObj.cloneContents();
    document.body.appendChild(documentFragment);
  • cloneRange()

    Return a Range object (changes made to each of the two objects will not affect the other).

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    clone = rangeObj.cloneRange(); 
  • collapse(toStart)

    Range towards the beginning or end.

    parameter:

    toStart : Alternatively, Boolean (default false ), true folded Range start direction, false folded end direction.

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    rangeObj.collapse(true);
  • compareBoundaryPoints(how, sourceRange)

    Compare the start position node or end position node of Range

    parameter:

    how represents the constant of the comparison method:

      Range.END_TO_END :比较 sourceRange 对象的结束位置节点和原 Range 对象的结束位置节点。
      Range.END_TO_START :比较 sourceRange 对象的结束位置节点和原 Range 对象的起始位置节点。
      Range.START_TO_END :比较 sourceRange 对象的起始位置节点和原 Range 对象的结束位置节点。
      Range.START_TO_START :比较 sourceRange 对象的起始位置节点和原 Range 对象的起始位置节点。       

    sourceRange Range object compared with the original Range object.

    return value

    compare represents a number:

      -1 :原 Range 对象的比较节点在 sourceRange 对象的比较节点之前  
      0 :原 Range 对象的比较节点在 sourceRange 对象的比较节点的相同位置   
      1 :原 Range 对象的比较节点在 sourceRange 对象的比较节点之后  

    Example:

    <div id="range">range</div>
    <div id="sourceRange">sourceRange</div>
    var range, sourceRange, compare;
    range = document.createRange();
    range.selectNode(document.querySelector("#rang"));
    sourceRange = document.createRange();
    sourceRange.selectNode(document.querySelector("#sourceRange"));
    compare = range.compareBoundaryPoints(Range.START_TO_END, sourceRange);
  • comparePoint(referenceNode,offset)

    Determine whether the specified node is in the Range , the same or the back position of the 060d2ff4287d63 object.

    parameter:

    referenceNode : The node to compare with the Range
    offset : The offset referenceNode
    If referenceNode is a text node or a comment node, offset represents the offset position of the character in the node.
    If referenceNode is an element node, offset represents the offset position of the child element in the node.

    Example:

    <div id="range">range</div>
    <div id="referenceNode">referenceNode</div>
    range = document.createRange();
    range.selectNode(document.querySelector("#range"));
    returnValue = range.comparePoint(document.querySelector("#referenceNode"), 0);
  • createContextualFragment(tagString)

    Convert HTML string to document fragment

    parameter:

    tagString HTML string to be converted.

    Example:

    var tagString = "<div>node</div>";
    var range = document.createRange();
    var documentFragment = range.createContextualFragment(tagString);
    document.body.appendChild(documentFragment);
  • deleteContents()

    Delete the selected document fragment from DOM , and do not return the deleted document fragment.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    rangeObj.deleteContents();
  • extractContents()

    Delete the selected document fragment from DOM and return the deleted document fragment ( DOM event is not retained).

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    rangeObj.extractContents();
  • getBoundingClientRect()

    Returns a DOMRect object, which represents the location information of the entire selection.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var boundingRect = rangeObj.getBoundingClientRect();
  • getClientRects()

    Returns a list of the results of Element.getClientRects() method for all elements in the selection. Indicates the area occupied by the selection on the screen.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var boundingRect = rangeObj.getClientRects();
  • insertNode(newNode)

    Insert a node at the beginning of the selection.

    parameter:

    newNode : The node that needs to be inserted

    Example:

    <div id="insertNode">insertNode</div>
    <div id="node">node</div>
    range = document.createRange();
    newNode = document.querySelector("#node");
    range.selectNode(document.querySelector("#insertNode"));
    range.insertNode(newNode);
  • intersectsNode(referenceNode)

    Return a Boolean value to determine whether the specified node and the Range object intersect.

    parameter:

    referenceNode : The node that needs to be compared

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.intersectsNode(referenceNode);
  • isPointInRange(referenceNode,offset)

    Return a Boolean value to determine whether the specified node is in the Range object.

    parameter:

    referenceNode : Specify the node
    offset : the offset referenceNode
    If referenceNode is a text node, offset represents the offset position of the character in the node.
    If referenceNode is an element node, offset represents the offset position of the child element in the node.

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.isPointInRange(referenceNode,0);
  • selectNode(referenceNode)

    Include the specified node in the Range object.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.selectNode(referenceNode);
  • selectNodeContents(referenceNode)

    Include the content of the specified node in the Range object.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.selectNodeContents(referenceNode);
  • setEnd(endNode,endOffset)

    Set the ending position of the selection.

    parameter:

    endNode : the node where the end position is located
    endOffset : the offset endNode
    If endNode is a text node or a comment node, endOffset represents the offset position of the character in the node.
    If endNode is an element node, endOffset represents the offset position of the child element in the node.

    Example:

    <div id="endNode">endNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var endNode = document.querySelector("#endNode");
    rangeObj.setEnd(endNode,0)
  • setEndAfter(referenceNode)

    Set the end position of the selection area after the specified node.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var referenceNode = document.querySelector("#referenceNode");
    rangeObj.setEndAfter(referenceNode)
  • setEndBefore(referenceNode)

    Set the end position of the selection before the specified node.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var referenceNode = document.querySelector("#referenceNode");
    rangeObj.setEndBefore(referenceNode)
  • setStart(startNode,startOffset)

    Set the starting position of the selection.

    parameter:

    startNode : the node where the starting position is located
    startOffset : The offset startNode
    If startNode is a text node or a comment node, startOffset represents the offset position of the character in the node.
    If startNode is an element node, startOffset represents the offset position of the child element in the node.

    Example:

    <div id="startNode">startNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    startNode = document.querySelector("#startNode");
    rangeObj.setStart(startNode,0)
  • setStartAfter(referenceNode)

    Set the starting position of the selection area after the specified node.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.setStartAfter(referenceNode)
  • setStartBefore(referenceNode)

    Set the starting position of the selection before the specified node.

    parameter:

    referenceNode : Specify the node

    Example:

    <div id="referenceNode">referenceNode</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    referenceNode = document.querySelector("#referenceNode");
    rangeObj.setStartBefore(referenceNode)
  • surroundContents(newParent)

    Insert the specified node into the beginning of the selection, and then replace the content of the specified node with the content of the selection.

    parameter:

    newParent : Specify the node

    Example:

    <div id="newParent">newParent</div>
    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    newParent = document.querySelector("#newParent");
    rangeObj.surroundContents(newParent)
  • toString()

    Returns the string representing the current Range object, such as the currently selected text.

    parameter:

    no

    Example:

    var selObj = window.getSelection();
    var rangeObj  = selObj.getRangeAt(0);
    var rangeStr = rangeObj.toString();

Multiple areas in the selection

A Selection object represents a collection of areas selected by the user ( Range objects). Usually it only contains one area. The access method is as follows:

//获取一个 Selection 对象
var selObj = window.getSelection();
//获取一个 Range 对象
var rangeObj  = selObj.getRangeAt(0);

Only Firefox implements multiple areas, as shown in the figure below:

多个区域

Modify selection style

Use ::selection selector to match the selected part.
Currently only a small number of CSS properties can be used for ::selection selectors:

Example

example address

reference

Selection

Range

notes JavaScript Selection object: basic attributes

Use javascript to realize rich text editor

What is anchorNode , baseNode , extentNode and focusNode in the object returned by document.getSelection?

Coordinates of selected text in browser page


FEWY
4.7k 声望443 粉丝