


A brief discussion on how to operate the cursor and selection in JavaScript?
How to operate the cursor and selection in JavaScript? The following article will take you through the Selection object and Range object, and introduce how to use these two objects to operate the cursor and selection.
When you need to operate the cursor and selection in some business scenarios, such as highlighting text, input editing, etc., you can use the Selection provided by the browser
objects and Range
objects to operate the cursor and selection.
Selection Object
Selection
The object represents the user-selected selection or the current position of the caret, which may span multiple elements.
//获取 Selection 对象 window.getSelection();
A user may select text from left to right (same direction as the document) or from right to left (opposite to the direction of the document).
anchor
(anchor): refers to the place where the user starts selecting. 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. The concepts of anchor
and focus
should not be confused with the starting and ending positions of the selection, because anchor
may be in front of focus
, as well as It may be after focus
, depending on the direction of the mouse movement when you select the text, that is, where the mouse button is pressed and released.
As shown below:
## Attributes:
- anchorNode: The node where the anchor point (anchor
) is located.
-
anchorOffset:
- If
- anchorNode
is a text node or annotation node, return the anchor point (
anchor) to the number of characters of the first word in the node.
If - anchorNode
is an element node, return the total number of sibling nodes before the anchor point (
anchor).
- anchorNode
- focusNode: The node where the focus (focus
) is located.
-
focusOffset:
- If
- focusNode
is a text node or annotation node, return the focus (
focus) The number of characters to the first word in this node.
If - focusNode
is an element node, return the total number of sibling nodes before focus (
focus).
- focusNode
- isCollapsed: A Boolean
value indicating whether the starting position and ending position of the selection coincide, if it is
true, it can be considered that no content is currently selected.
- rangeCount: The number of Range
objects contained in the selection.
-
type: Describes the type of the current selection, with the following three values:
- None: There is currently no selection.
- Caret: Only clicked, but not selected, and the selection is collapsed (that is, the cursor is between characters and is not selected).
- Range: The selection is a range.
Note:
All the above attributes areread-only attributes.
Method:
- addRange(range)Add to the selection (
Selection
Parameters:object) A range (
Rangeobject).
range
Example:: A range object
<p id="text">文本</p>
Copy after login//添加一个选区 var text = document.querySelector("#text"); var selObj = window.getSelection(); var rangeObj = document.createRange(); rangeObj.selectNode(text); selObj.addRange(rangeObj);
Copy after login - collapse(parentNode, offset)Collapse the current selection to a point. The document will not be changed. Parameters:
parentNode
Example:: The target node where the cursor falls
offset: Optional, offset within the target node
<div contenteditable="true" id="text">文本</div>
Copy after login//收起选区到一个点,光标落在一个可编辑元素上 var text = document.querySelector("#text") window.getSelection().collapse(text,0);
Copy after login - collapseToEnd()Cancel the current selection and position the cursor at the end of the original selection. Parameters: NoneExample:
var selObj = window.getSelection(); selObj.collapseToEnd();
Copy after login - collapseToStart()Cancel the current selection and Position the cursor at the beginning of the original selection. Parameters: NoneExample:
var selObj = window.getSelection(); selObj.collapseToStart();
Copy after login##containsNode(aNode,aPartlyContained) Judgment specification Whether the node is included in the
Selectionobject (that is, whether it is selected).
<h4 id="参数">参数:</h4><p><code>aNode
: 用于判断是否包含在Selection
对象中的节点。aPartlyContained
:
当此参数为true
时,Selection
对象包含aNode
的一部分或全部时,containsNode()
方法返回true
。
当此参数为false
(默认值)时,只有Selection
对象完全包含aNode
时,containsNode()
方法才返回true
。示例:
<div id="text">文本</div>
Copy after loginCopy after loginvar text = document.querySelector("#text"); var selObj = window.getSelection(); var contains = selObj.containsNode(text);
Copy after logindeleteFromDocument()
从
DOM
中删除选中的文档片段。参数:
无
示例:
var selObj = window.getSelection(); selObj.deleteFromDocument();
Copy after loginextend(node,offset)
移动选区的焦点(
focus
)到指定的点。选区的锚点(anchor
)不会移动。选区将从锚点(anchor
)开始到新的焦点(focus
),不管方向。参数:
node
: 焦点(focus
)会被移至此节点内。offset
: 可选,默认值为0,焦点(focus
)会被移至node
内的偏移位置。示例:
<div id="text">文本</div>
Copy after loginCopy after loginvar text = document.querySelector("#text"); var selObj = window.getSelection(); selObj.extend(text);
Copy after logingetRangeAt(index)
返回一个当前选区包含的
Range
对象。参数:
index
: 该参数指定Range
对象的索引。如果该数值大于或等于rangeCount
,将会报错。示例:
//获取一个 Selection 对象 var selObj = window.getSelection(); //获取一个 Range 对象 var rangeObj = selObj.getRangeAt(0);
Copy after loginmodify(alter,direction,granularity)
通过文本命令来更改当前选区或光标位置。
参数:
alter
:改变类型,传入move
来移动光标位置,或者extend
来扩展当前选区。direction
:调整选区的方向。你可以传入forward
或backward
来根据选区内容的语言书写方向来调整。或者使用left
或right
来指明一个明确的调整方向。granularity
:调整的距离颗粒度。可选值有character
、word
、sentence
、line
、paragraph
、lineboundary
、sentenceboundary
、paragraphboundary
、documentboundary
。示例:
var selection = window.getSelection(); selection.modify("extend", "forward", "word");
Copy after login
removeAllRanges()
会从当前
Selection
对象中移除所有的Range
对象,取消所有的选择。参数:
无
示例:
var selObj = window.getSelection(); selObj.removeAllRanges();
Copy after loginremoveRange(range)
将一个
Range
对象从选区中移除。参数:
range
: 一个将从选区中移除的Range
对象。示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0) selObj.removeRange(rangeObj);
Copy after login
selectAllChildren(parentNode)
把指定元素的所有子元素设置为选区(该元素本身除外),并取消之前的选区。
参数:
parentNode
: 指定元素示例:
<div id="selectAll"> <div>文本1</div> <div>文本2</div> </div>
Copy after loginvar selectAll = document.querySelector("#selectAll"); var selObj = window.getSelection(); selObj.selectAllChildren(selectAll);
Copy after loginsetBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset)
选中两个特定
DOM
节点之间的内容。参数:
anchorNode
: 选中内容的开始节点anchorOffset
:选区起始位置在anchorNode
内的偏移量。
如果anchorNode
是文本节点,表示选区起始位置在该节点第几个字符位置。
如果anchorNode
是元素节点,表示选区起始位置在该节点内第几个子节点的位置。focusNode
: 选中内容的结束节点focusOffset
: 选区终止位置在focusNode
内的偏移量。
如果focusNode
是文本节点,表示选区终止位置在该节点第几个字符位置。
如果focusNode
是元素节点,表示选区终止位置在该节点内第几个子节点的位置。
示例:
<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()
返回代表当前
Selection
对象的字符串,例如当前选择的文本。参数:
无
示例:
var selObj = window.getSelection(); selObj.toString();
Copy after login
Range 对象
Range
对象表示被选中的文档片段。一个 Range
对象可能包含整个元素节点,也可能包含元素节点的一部分,例如文本节点的一部分文字。用户通常只能选择一个 Range
对象,但是有的时候用户也有可能选择多个 Range
对象(只有火狐浏览器可以选择多个 Range
对象)。
可以用 Document 对象的 Document.createRange 方法创建 Range
,也可以用 Selection 对象的 getRangeAt 方法获取 Range
。另外,还可以通过 Document 对象的构造函数 Range() 来得到 Range
。
属性:
- collapsed: 返回一个表示起始位置和终止位置是否相同的
Boolean
值。 - commonAncestorContainer: 返回包含
startContainer
和endContainer
的最深一级的节点。 - endContainer: 返回包含
Range
终点位置的节点。 endOffset:
- 如果
endContainer
是文本节点、注释节点,返回该节点第一个字到选区边界的字符个数(即被选中的字符个数)。 - 如果
endContainer
是元素节点,返回选区终止位置之后第一个节点之前的同级节点总数。
- 如果
- startContainer: 返回包含
Range
开始位置的节点。 startOffset:
- 如果
startContainer
是文本节点、注释节点,返回该节点第一个字到选区边界的字符个数(即未被选中的字符个数)。 - 如果
startContainer
是元素节点,返回选区起始位置第一个节点之前的同级节点总数。
- 如果
注意:
以上所有属性都是只读属性。
方法:
cloneContents()
返回一个文档片段,它是
Range
对象中所有节点的副本。参数:
无
示例:
// 在文档中插入选中元素 var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); documentFragment = rangeObj.cloneContents(); document.body.appendChild(documentFragment);
Copy after logincloneRange()
返回一个
Range
对象的副本(两个对象各自做出改变,都不会影响另一方)。参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); clone = rangeObj.cloneRange();
Copy after logincollapse(toStart)
向开始或结束方向折叠
Range
。参数:
toStart
: 可选,Boolean
值(默认值false
),true
折叠到Range
的开始方向,false
折叠到结束方向。示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); rangeObj.collapse(true);
Copy after logincompareBoundaryPoints(how, sourceRange)
比较两个
Range
对象的起始位置节点或结束位置节点。参数:
how
表示比较方法的常量:Range.END_TO_END :比较 sourceRange 对象的结束位置节点和原 Range 对象的结束位置节点。 Range.END_TO_START :比较 sourceRange 对象的结束位置节点和原 Range 对象的起始位置节点。 Range.START_TO_END :比较 sourceRange 对象的起始位置节点和原 Range 对象的结束位置节点。 Range.START_TO_START :比较 sourceRange 对象的起始位置节点和原 Range 对象的起始位置节点。
Copy after loginsourceRange
: 一个与原Range
对象比较的Range
对象。返回值
compare
表示一个数字:-1 :原 Range 对象的比较节点在 sourceRange 对象的比较节点之前 0 :原 Range 对象的比较节点在 sourceRange 对象的比较节点的相同位置 1 :原 Range 对象的比较节点在 sourceRange 对象的比较节点之后
Copy after login示例:
<div id="range">range</div> <div id="sourceRange">sourceRange</div>
Copy after loginvar 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);
Copy after login
comparePoint(referenceNode,offset)
判断指定节点是在
Range
对象的之前、相同还是之后位置。参数:
referenceNode
: 与Range
对象进行比较的节点。offset
: 在referenceNode
内的偏移量。
如果referenceNode
是文本节点、注释节点,offset
表示在该节点中字符的偏移位置。
如果referenceNode
是元素节点,offset
表示在该节点中子元素的偏移位置。示例:
<div id="range">range</div> <div id="referenceNode">referenceNode</div>
Copy after loginrange = document.createRange(); range.selectNode(document.querySelector("#range")); returnValue = range.comparePoint(document.querySelector("#referenceNode"), 0);
Copy after logincreateContextualFragment(tagString)
将
HTML
字符串转换为文档片段参数:
tagString
: 要转换的HTML
字符串。示例:
var tagString = "<div>node</div>"; var range = document.createRange(); var documentFragment = range.createContextualFragment(tagString); document.body.appendChild(documentFragment);
Copy after logindeleteContents()
从
DOM
中删除选中的文档片段,不返回删除的文档片段。参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); rangeObj.deleteContents();
Copy after loginextractContents()
从
DOM
中删除选中的文档片段,返回删除的文档片段(不保留DOM
事件)。参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); rangeObj.extractContents();
Copy after logingetBoundingClientRect()
返回一个 DOMRect 对象,表示整个选区的位置信息。
参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var boundingRect = rangeObj.getBoundingClientRect();
Copy after logingetClientRects()
返回一个选区内所有元素调用 Element.getClientRects() 方法所得结果的列表。表示选区在屏幕上所占的区域。
参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var boundingRect = rangeObj.getClientRects();
Copy after logininsertNode(newNode)
在选区开始处插入一个节点。
参数:
newNode
: 需要插入的节点示例:
<div id="insertNode">insertNode</div> <div id="node">node</div>
Copy after loginrange = document.createRange(); newNode = document.querySelector("#node"); range.selectNode(document.querySelector("#insertNode")); range.insertNode(newNode);
Copy after loginintersectsNode(referenceNode)
返回一个
Boolean
值,判断指定节点和Range
对象是否相交。参数:
referenceNode
:需要比较的节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.intersectsNode(referenceNode);
Copy after loginisPointInRange(referenceNode,offset)
返回一个
Boolean
值,判断指定节点是否在Range
对象内。参数:
referenceNode
:指定节点offset
:在referenceNode
内的偏移量。
如果referenceNode
是文本节点,offset
表示在该节点中字符的偏移位置。
如果referenceNode
是元素节点,offset
表示在该节点中子元素的偏移位置。示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.isPointInRange(referenceNode,0);
Copy after login
selectNode(referenceNode)
将指定节点包含在
Range
对象内。参数:
referenceNode
:指定节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.selectNode(referenceNode);
Copy after loginselectNodeContents(referenceNode)
将指定节点的内容包含在
Range
对象内。参数:
referenceNode
:指定节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.selectNodeContents(referenceNode);
Copy after loginsetEnd(endNode,endOffset)
设置选区的终止位置。
参数:
endNode
:终止位置所在的节点endOffset
:在endNode
内的偏移量。
如果endNode
是文本节点、注释节点,endOffset
表示在该节点中字符的偏移位置。
如果endNode
是元素节点,endOffset
表示在该节点中子元素的偏移位置。示例:
<div id="endNode">endNode</div>
Copy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var endNode = document.querySelector("#endNode"); rangeObj.setEnd(endNode,0)
Copy after login
setEndAfter(referenceNode)
设置选区的结束位置在指定节点之后。
参数:
referenceNode
:指定节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var referenceNode = document.querySelector("#referenceNode"); rangeObj.setEndAfter(referenceNode)
Copy after loginsetEndBefore(referenceNode)
设置选区的结束位置在指定节点之前。
参数:
referenceNode
:指定节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var referenceNode = document.querySelector("#referenceNode"); rangeObj.setEndBefore(referenceNode)
Copy after loginsetStart(startNode,startOffset)
设置选区的起始位置。
参数:
startNode
:起始位置所在的节点startOffset
:在startNode
内的偏移量。
如果startNode
是文本节点、注释节点,startOffset
表示在该节点中字符的偏移位置。
如果startNode
是元素节点,startOffset
表示在该节点中子元素的偏移位置。示例:
<p id="startNode">startNode</p>
Copy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); startNode = document.querySelector("#startNode"); rangeObj.setStart(startNode,0)
Copy after loginsetStartAfter(referenceNode)
设置选区的起始位置在指定节点之后。
参数:
referenceNode
:指定节点示例:
<div id="startNode">startNode</div>
Copy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.setStartAfter(referenceNode)
Copy after loginsetStartBefore(referenceNode)
设置选区的起始位置在指定节点之前。
参数:
referenceNode
:指定节点示例:
<div id="referenceNode">referenceNode</div>
Copy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginCopy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); referenceNode = document.querySelector("#referenceNode"); rangeObj.setStartBefore(referenceNode)
Copy after loginsurroundContents(newParent)
把指定节点插入选区的起始位置,然后把指定节点的内容替换为选区的内容。
参数:
newParent
:指定节点示例:
<div id="newParent">newParent</div>
Copy after loginvar selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); newParent = document.querySelector("#newParent"); rangeObj.surroundContents(newParent)
Copy after logintoString()
返回代表当前
Range
对象的字符串,例如当前选择的文本。参数:
无
示例:
var selObj = window.getSelection(); var rangeObj = selObj.getRangeAt(0); var rangeStr = rangeObj.toString();
Copy after login
选区中的多个区域
一个 Selection
对象表示用户选择的区域(Range
对象)的集合,通常它只包含一个区域,访问方式如下:
//获取一个 Selection 对象 var selObj = window.getSelection(); //获取一个 Range 对象 var rangeObj = selObj.getRangeAt(0);
只有火狐浏览器实现了多个区域,如下图所示:
修改选区样式
使用 ::selection 选择器可以匹配被选中的部分。
目前只有一小部分 CSS 属性可以用于 ::selection 选择器:
- color
- background-color
- text-shadow
示例
示例地址:https://www.kkkk1000.com/images/SelectionRange/selection.html
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of A brief discussion on how to operate the cursor and selection in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The Windows 7 system has currently stopped updating, so if there is a problem, you can only solve it yourself. As shown below, there are many situations where the cursor goes black after booting the computer, and you need to troubleshoot one by one. If you don’t want to spend time troubleshooting, you can just reinstall the system. What to do if there is only a black screen with a cursor when Windows 7 starts up? The first solution: Restart the computer, and immediately press and hold the "F8" button on the keyboard after restarting. Then select "Last Known Good Configuration" in the advanced system menu. The second solution: press the shortcut key "CTRL+SHIFT+ESC" to see if the task manager can be brought up. If so, right-click to end Explorer.exe in the process and then create a new run Explorer.exe to try.

What is Xfce? Xfce is a free software that runs on Unix-like operating systems (such as Linux, FreeBSD and Solaris) and provides a lightweight desktop environment. How to adjust the cursor color in Debian11Xfce terminal? Let’s take a look at the specific operations with the editor. Click [Edit]-[Preferences]. Switch to the [Color] tab. Check Customize [Cursor Color] and click the color selection button on the right. After opening the palette, click to select the cursor color you want to set.
