Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How JavaScript manipulates cursors and selections

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "JavaScript how to operate the cursor and selection", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "JavaScript how to operate the cursor and selection" article.

When you need to manipulate the cursor and selection in some business scenarios, such as highlighted text, input editing, and so on, you can use the Selection object and Range object provided by the browser to manipulate the cursor and selection.

Selection object

The Selection object represents the current location of the selection or caret selected by the user, which may span multiple elements.

/ / get Selection object window.getSelection ()

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

Anchor (anchor point): refers to the place where the user starts to select.

Focus: refers to the place where the user ends the selection.

If you use the mouse to select text, anchor is where you press the mouse button, and focus is where you release the mouse button. The concepts of anchor and focus should not be confused with the start and end positions of the selection, because the anchor may be in front of the focus or behind the focus, depending on the direction in which you move the mouse when you select the text, that is, where you press and release the mouse button.

As shown in the following figure:

Attributes:

AnchorNode: the node where the anchor point (anchor) is located.

AnchorOffset:

If anchorNode is a text node, comment node, returns the number of characters from the anchor point (anchor) to the first word in that node.

If anchorNode is an element node, returns the total number of sibling nodes before the anchor point (anchor).

FocusNode: the node where the focus is located.

FocusOffset:

If focusNode is a text node, comment node, returns the number of characters focus to the first word in that node.

If focusNode is an element node, returns the total number of sibling nodes before the focus.

IsCollapsed: a Boolean value indicating whether the start and end positions of the selection coincide. If true, no content is currently selected.

RangeCount: the number of Range objects contained in the selection.

Type: describes the type of the current selection, with three values:

None: there is currently no choice.

Caret: click only, but not selected, and the selection is collapsed (that is, the cursor is between characters and is not selected).

Range: select a range.

Note:

All of the above properties are read-only.

Method: addRange (range)

Add a region (Range object) to the selection (Selection object).

Parameters:

Range: a region object

Example: text

/ / add a selection var text = document.querySelector ("# text"); var selObj = window.getSelection (); var rangeObj = document.createRange (); rangeObj.selectNode (text); selObj.addRange (rangeObj); collapse (parentNode,offset)

Fold the current selection to a point. The document does not change.

Parameters:

ParentNode: the target node where the cursor falls

Offset: optional, offset within the target node

Example: text / / collapses the selection to a point, and the cursor falls on an editable element 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.

Parameters:

None

Example: var selObj = window.getSelection (); selObj.collapseToEnd (); collapseToStart ()

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

Parameters:

None

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

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

Parameters:

ANode: a node used to determine whether it is included in a Selection object.

APartlyContained:

When this parameter is true, the containsNode () method returns true when the Selection object contains some or all of the aNode.

When this parameter is false (the default), the containsNode () method returns true only if the Selection object fully contains aNode.

Example: text var text = document.querySelector ("# text"); var selObj = window.getSelection (); var contains = selObj.containsNode (text); deleteFromDocument ()

Removes the selected document fragment from the DOM.

Parameters:

None

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

Moves the focus (focus) of the selection to the specified point. The anchor point (anchor) of the selection does not move. The selection starts from the anchor point (anchor) to the new focus (focus), regardless of direction.

Parameters:

Node: the focus (focus) is moved to this node.

Offset: optional, the default is 0, and the focus (focus) will be moved to the offset position within the node.

Example: text var text = document.querySelector ("# text"); var selObj = window.getSelection (); selObj.extend (text); getRangeAt (index)

Returns a Range object contained in the current selection.

Parameters:

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

Example: / / get a Selection object var selObj = window.getSelection (); / / get a Range object var rangeObj = selObj.getRangeAt (0); modify (alter,direction,granularity)

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

Parameters:

Alter: change the type, pass in move to move the cursor position, or extend to expand the current selection.

Direction: reorients the selection. You can input forward or backward to adjust according to the language writing direction of the selection content. Or use left or right to indicate a clear direction of adjustment.

Granularity: adjusted distance granularity. Available values are character, word, sentence, line, paragraph, lineboundary, sentenceboundary, paragraphboundary, documentboundary.

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

Removes all Selection objects from the current Range object and deselects all selections.

Parameters:

None

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

Removes a Range object from the selection.

Parameters:

Range: a Range object that will be removed from the selection.

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

Sets all child elements of the specified element to a selection (except the element itself) and cancels the previous selection.

Parameters:

ParentNode: specify element

Example: text 1 text 2var selectAll = document.querySelector ("# selectAll"); var selObj = window.getSelection (); selObj.selectAllChildren (selectAll); setBaseAndExtent (anchorNode,anchorOffset,focusNode,focusOffset)

Select the content between two specific DOM nodes.

Parameters:

AnchorNode: the start node of the selected content

AnchorOffset: the offset of the starting position of the selection within the anchorNode.

If the anchorNode is a text node, which character of the node is the starting position of the selection.

If anchorNode is an element node, it indicates that the starting position of the selection is in the position of the first child node within that node.

FocusNode: the end node of the selected content

FocusOffset: the offset of the end position of the selection within the focusNode.

If focusNode is a text node, it indicates the character of the node where the selection terminates.

If focusNode is an element node, it indicates the location of the child node in which the selection terminates.

Example: var start = document.querySelector ("# start"); var end = document.querySelector ("# end"); var selObj = window.getSelection (); selObj.setBaseAndExtent (start,0,end,0); toString ()

Returns a string that represents the current Selection object, such as the text of the current selection.

Parameters:

None

Example: var selObj = window.getSelection (); selObj.toString (); Range object

The Range object represents the selected document fragment. A Range object may contain the entire element node, or it may contain part of the element node, such as part of the text node. Users can usually select only one Range object, but sometimes it is possible for users to select multiple Range objects (only Firefox can select multiple Range objects).

You can use the Document.createRange method of the Document object to create the Range, or you can use the getRangeAt method of the Selection object to get the Range. In addition, you can get the Range through the constructor Range () of the Document object.

Attributes:

Collapsed: returns a Boolean value indicating whether the start position and the end position are the same.

CommonAncestorContainer: returns the node with the deepest level of startContainer and endContainer.

EndContainer: returns the node that contains the end location of the Range.

EndOffset:

If endContainer is a text node, comment node, returns the number of characters from the first word of the node to the selection boundary (that is, the number of characters selected).

If endContainer is an element node, returns the total number of sibling nodes before the first node after the end of the selection.

StartContainer: returns the node that contains the starting position of the Range.

StartOffset:

If startContainer is a text node, comment node, returns the number of characters from the first word of the node to the selection boundary (that is, the number of characters that are not selected).

If startContainer is an element node, returns the total number of sibling nodes before the first node at the start of the selection.

Note:

All of the above properties are read-only.

Method: cloneContents ()

Returns a document fragment that is a copy of all nodes in the Range object.

Parameters:

None

Example: / / insert selected elements var selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); documentFragment = rangeObj.cloneContents (); document.body.appendChild (documentFragment); cloneRange () in the document

Returns a copy of the Range object (each of the two objects makes changes without affecting the other).

Parameters:

None

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

Collapses the Range toward the start or end.

Parameters:

ToStart: optional, Boolean value (default false), true collapses to the start direction of the Range, false collapses to the end direction.

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

Compares the start position node or end position node of two Range objects.

Parameters:

How represents the constant of the comparison method:

Range.END_TO_END: compares the end position node of the sourceRange object with that of the original Range object. Range.END_TO_START: compares the end position node of the sourceRange object with the start position node of the original Range object. Range.START_TO_END: compares the start position node of the sourceRange object with the end position node of the original Range object. Range.START_TO_START: compares the start position node of the sourceRange object with the start position node of the original Range object.

SourceRange: a Range object compared to the original Range object.

Return value

Compare represents a number:

-1: the comparison node of the original Range object is before the comparison node of the sourceRange object 0: the comparison node of the original Range object is in the same position as the comparison node of the sourceRange object 1: the comparison node of the original Range object is after the comparison node of the sourceRange object example: rangesourceRangevar range, sourceRange, compare;range = document.createRange (); range.selectNode (document.querySelector ("# rang")); sourceRange = document.createRange (); sourceRange.selectNode ("# sourceRange")) Compare = range.compareBoundaryPoints (Range.START_TO_END, sourceRange); comparePoint (referenceNode,offset)

Determines whether the specified node is positioned before, the same, or after the Range object.

Parameters:

ReferenceNode: the node that is compared to the Range object.

Offset: the offset within the referenceNode.

If the referenceNode is a text node, a comment node, offset represents the offset position of the characters in that node.

If referenceNode is an element node, offset represents the offset of the child elements in that node.

Example: rangereferenceNoderange = document.createRange (); range.selectNode (document.querySelector ("# range")); returnValue = range.comparePoint (document.querySelector ("# referenceNode"), 0); createContextualFragment (tagString)

Convert an HTML string to a document fragment

Parameters:

TagString: the HTML string to convert.

Example: var tagString = "node"; var range = document.createRange (); var documentFragment = range.createContextualFragment (tagString); document.body.appendChild (documentFragment); deleteContents ()

Deletes the selected document fragment from the DOM and does not return the deleted document fragment.

Parameters:

None

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

Deletes the selected document fragment from the DOM and returns the deleted document fragment (without retaining the DOM event).

Parameters:

None

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

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

Parameters:

None

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

Returns a list of the results obtained by calling the Element.getClientRects () method for all elements in a selection. Represents the area that the selection occupies on the screen.

Parameters:

None

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.

Parameters:

NewNode: the node to be inserted

Example: insertNodenoderange = document.createRange (); newNode = document.querySelector ("# node"); range.selectNode (document.querySelector ("# insertNode")); range.insertNode (newNode); intersectsNode (referenceNode)

Returns a Boolean value to determine whether the specified node intersects the Range object.

Parameters:

ReferenceNode: nodes to be compared

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.intersectsNode (referenceNode); isPointInRange (referenceNode,offset)

Returns a Boolean value to determine whether the specified node is within the Range object.

Parameters:

ReferenceNode: specify nod

Offset: the offset within the referenceNode.

If referenceNode is a text node, offset represents the offset position of the characters in that node.

If referenceNode is an element node, offset represents the offset of the child elements in that node.

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.isPointInRange (referenceNode,0); selectNode (referenceNode)

Includes the specified node in the Range object.

Parameters:

ReferenceNode: specify nod

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.selectNode (referenceNode); selectNodeContents (referenceNode)

Includes the contents of the specified node in the Range object.

Parameters:

ReferenceNode: specify nod

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.selectNodeContents (referenceNode); setEnd (endNode,endOffset)

Sets the termination position of the selection.

Parameters:

EndNode: the node where the termination location is located

EndOffset: the offset within the endNode.

If the endNode is a text node, a comment node, endOffset represents the offset position of the characters in that node.

If endNode is an element node, endOffset represents the offset of the child elements in that node.

Example: endNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); var endNode = document.querySelector ("# endNode"); rangeObj.setEnd (endNode,0) setEndAfter (referenceNode)

Sets the end of the selection after the specified node.

Parameters:

ReferenceNode: specify nod

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); var referenceNode = document.querySelector ("# referenceNode"); rangeObj.setEndAfter (referenceNode) setEndBefore (referenceNode)

Sets the end of the selection before the specified node.

Parameters:

ReferenceNode: specify nod

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); var referenceNode = document.querySelector ("# referenceNode"); rangeObj.setEndBefore (referenceNode) setStart (startNode,startOffset)

Sets the starting position of the selection.

Parameters:

StartNode: the node where the starting position is located

StartOffset: the offset within the startNode.

If the startNode is a text node, a comment node, startOffset represents the offset position of the characters in that node.

If startNode is an element node, startOffset represents the offset of the child elements in that node.

Example: startNode

Var selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); startNode = document.querySelector ("# startNode"); rangeObj.setStart (startNode,0) setStartAfter (referenceNode)

Sets the starting position of the selection after the specified node.

Parameters:

ReferenceNode: specify nod

Example: startNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.setStartAfter (referenceNode) setStartBefore (referenceNode)

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

Parameters:

ReferenceNode: specify nod

Example: referenceNodevar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); referenceNode = document.querySelector ("# referenceNode"); rangeObj.setStartBefore (referenceNode) surroundContents (newParent)

Inserts the specified node into the starting position of the selection, and then replaces the contents of the specified node with the contents of the selection.

Parameters:

NewParent: specify nod

Example: newParentvar selObj = window.getSelection (); var rangeObj = selObj.getRangeAt (0); newParent = document.querySelector ("# newParent"); rangeObj.surroundContents (newParent) toString ()

Returns a string that represents the current Range object, such as the text of the current selection.

Parameters:

None

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 object), which usually contains only one area and is accessed as follows:

/ / get a Selection object var selObj = window.getSelection (); / / get a Range object var rangeObj = selObj.getRangeAt (0)

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

Modify selection styl

Use the:: selection selector to match the selected section.

Currently, only a small number of CSS attributes are available for the:: selection selector:

Color

Background-color

Text-shadow

Example

The above is about the content of this article on "how to manipulate the cursor and selection of JavaScript". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report