What is the usage of range in javascript

藏色散人
Release: 2022-01-18 11:44:14
Original
2772 people have browsed it

The range object of JavaScript refers to the area in the HTML document, and its usage method is such as "var elem=range.commonAncestorContainer;if(elem.nodeType != 1){...}".

What is the usage of range in javascript

The operating environment of this article: Windows 7 system, javascript version 1.8.5, Dell G3 computer.

What is the usage of range in javascript?

Usage of JS Range object

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:

What is the usage of range in javascript

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);
Copy after login

Three: range attribute

> collapsed     如果范围的开始点和结束点在文档的同一位置,则为 true,即范围是空的,或折叠的。
> commonAncestorContainer     范围的开始点和结束点的(即它们的祖先节点)、嵌套最深的 Document 节点。
> endContainer         包含范围的结束点的 Document 节点。 
> endOffset     endContainer 中的结束点位置。
> startContainer     包含范围的开始点的 Document 节点。
> startOffset    startContainer中的开始点位置。
Copy after login

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;
   }
}
Copy after login

Recommended study: "js basic tutorial"

The above is the detailed content of What is the usage of range in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!