1: What is the Range object
Range refers to The area in the html document, for example, the user drags the selected area with the mouse, as shown below:
Through the Range object, you can get the area selected by the user, or specify the selected area. Get the starting point and end point of the Range, modify or copy the text inside, even html. These functions are often used in rich text editor development.
Two: Get the current selection
Due to compatibility issues, it is necessary to distinguish between IE browsers,
var selection, range; if (window.getSelection) { //现代浏览器 selection = window.getSelection(); } else if (document.selection) { //IE selection = document.selection.createRange(); } //Range对象 range = selection.getRangeAt(0);
Three: range attribute
> collapsed 如果范围的开始点和结束点在文档的同一位置,则为 true,即范围是空的,或折叠的。 > commonAncestorContainer 范围的开始点和结束点的(即它们的祖先节点)、嵌套最深的 Document 节点。 > endContainer 包含范围的结束点的 Document 节点。 > endOffset endContainer 中的结束点位置。 > startContainer 包含范围的开始点的 Document 节点。 > startOffset startContainer中的开始点位置。
Four: range operation
//选中区域的文字 var text = range.toString(); //选中区域的Element元素 var elem = range.commonAncestorContainer; if(elem.nodeType != 1){ elem = elem.parentNode; } //选中区域的html var span = document.createElement('SPAN'); span.appendChild(range.cloneContents()); //选区是否为空 var isSelectionEmpty = false; if (range.startContainer === range.endContainer) { if (range.startOffset === range.endOffset) { isSelectionEmpty = true; } }