A study of Range objects in HTML5 (reproduced)

Source: Internet
Author: User

A: The concept of a Range object

The Range object represents a contiguous area on the page, and through the Range object, you can get or modify any area on the page by creating an empty Range object as follows:

var range = Document.createrange ();

In HTML5, each browser window and each window has a Selection object that represents the area selected by the user's mouse in the page ( Note: The browser below the test IE9 does not support selection objects ), you can create a Selection object from the following statement;

var selection = Document.getselection (); Or

var selection = Window.getselection ();

Each Selection object has one or more range objects, and each Range object represents a contiguous area within the range selected by the user's mouse, and in Firefox, multiple contiguous regions can be selected with the CTRL key. So in Firefox, a Selection object has multiple Range objects, and in other browsers, the user can only select a contiguous range, so there is only one Range object.

You can get a Range object for a Selection object by using the Getrangeat method of the Selection object, as follows:

var range = document.getselection (). getrangeat (index);

The Getrangeat method has a parameter index, which represents the serial number of the Range object, and we can determine whether the user has selected the content by the value of the Rangecount parameter of the Selection object.

    1. When the user does not press the mouse, the value of this parameter is 0.
    2. When the user presses the mouse, the parameter value is 1.
    3. When a user selects one or more regions while holding down the CTRL key while using the mouse, the parameter value represents the number of user-selected areas.
    4. When the user cancels the selection of the range, the property value is 1, representing an empty Range object on the page;

The following code tests:

Examples of usages of <input type= "button" value= "click Me" onclick= "rangetest ()"/>
<div id= "Showrange" ></div>

The JS code is as follows:

<script>   function rangetest () {        var  html,         Showrangediv = document.getElementById ("Showrange"),          selection = document.getselection ();        if ( Selection.rangecount > 0) {            html = "You have selected" + Selection.rangecount + "segment content <br/>";            for ( var i = 0; i < Selection.rangecount; i++) {                var range = Selection.getrangeat (i);                 HTML + + + (i + 1) + "segment content:" + range + "<br/>";          &nbsp ; }            showrangediv.innerhtml = html;       }   }</ Script>

As the above code, when the user selects a paragraph of text, click the button, will display the selected text, the following in Firefox effect:

In Chrome, it looks like this:

Two: Properties and methods of the Range object

The properties are as follows:

Collapsed (Boolean): Used to determine whether the Range object represents the beginning and end points of the region are in the same position, if the same property value returns true;

Commonancestorcontainer (node): Used to return the node in which the Range object represents the region, which is the node that contains the lowest layer node of the range (a node may be an element, or it may be a complete text).

EndContainer (node): Used to return the endpoint of the area represented by the Range object in what node, which is the lowest-level node that contains the end of the zone.

Endoffset (integer value type): Used to return the distance between the end of the area represented by the Range object and the starting point of the node that contains the end point.

Startcontainer (node): Used to return the starting point of the range represented by the Range object in the node, which is the lowest-level node that contains the beginning of the region.

Startoffset (integer value type): Used to return the distance between the starting point of the range represented by the Range object and the starting point of the node that contains the starting point.

There are many methods, the meaning of the method is more difficult to understand, I also see the book on this side of the writing, by the way, I did a demo try to understand the meaning of the next. Need to use in the future can look at it;

Selectnode method: The Selectnode method of the Range object is used to designate the start point of a Range object as the starting point of a node, specifying the end point of the Range object as the endpoint of that node, so that the region represented by the Range object contains the node. Here's how to use it:

Rangeobj.selectnode (node);

The rangeobj above represents a Range object that uses a parameter that represents a node in the page.

Selectnodecontents method: Used to designate the start point of a Range object as the starting point for all content in a node, specifying the end point of the Range object as the end point of all the contents of that node, so that the range represented by the Ranges object contains all the contents of that node. Here's how to use it:

Rangeobj.selectnodecontents (node);

The meaning is as shown above;

DeleteContents method: Used to remove content contained in a Range object from the page, using the following method:

Rangeobj.deletecontents ();

Let's do a demo below to understand the above three methods; The following code:

<div id= "div" style= "width:300px;height:50px;" Content in the > element </div><button onclick= "deleterangecontents (True)" > Delete content </button><button onclick= " Deleterangecontents (False) "> delete element </button>

The page appears as follows:

The JS code is as follows:

 <script>    function deleterangecontents (flag) {         var div = document.getElementById ("div");        var rangeobj = Document.createrange ();        if (flag) {                         // Selectnodecontents refers to selecting all content in the Range object   deleting it              Rangeobj.selectnodecontents (DIV);            Rangeobj.deletecontents ();       }else {             Rangeobj.selectnode (Div);             rangeobj.deletecontents ();       }   }</ Script> 

When the code finishes executing Document.createrange (), let's see what the value of the Rangeobj object is,

When you click Delete Content, the corresponding content is deleted, as follows:

The code executes to the following, and the value of the Rangeobj object becomes as follows:

When we click on the button to delete the element, as follows:

At this point the Rangeobj object becomes as follows:

Setstart method is used to designate a location in a node as the starting point for the range represented by the Range object, using the following method:

Rangeobj.setstart (Node,curindex);

As the above code Rangeobj represents a Range object, the Setstart method uses 2 parameters, the first parameter node represents a nodes, the second parameter is a number, and when the first parameter node represents a text node with a text content, The parameter value is used to specify the end position of the first text as the starting position of the area represented by the Range object, and when the first parameter, node, contains other child nodes, the value of the parameter is used to specify the end position of the number of child nodes as the starting position of the area represented by the Range object;

SetEnd method is used to specify where a Range object represents the end position of the range in a node. Use the following method:

Rangeobj.setend (Node,curindex);

The meaning of the 2 parameters in the method is the same as the parameters in the Setstart method, except that one is the starting position and the other is the end position;

Let's look at a demo to understand the meaning of the 2 methods above;

<div id= "Mydiv" > the third text in the text will be removed from the tenth text </div>
<button onclick= "Deletechar ()" > Delete text </button>

The JS code is as follows:

<script> function Deletechar () {var mydiv = document.getElementById ("mydiv");        var textnode = Mydiv.firstchild;        var rangeobj = Document.createrange ();        Rangeobj.setstart (textnode,2);        Rangeobj.setend (textnode,10);    Rangeobj.deletecontents (); }</script>

When we click the Delete Text button, the 3rd to 10th text is deleted ~

Setstartbefore method: used to designate the start position of a node as the starting point for the range represented by the Range object.

Setstartafter method: used to specify the end position of a node as the starting point for the range represented by the Range object.

Setendbefore method: used to designate the start position of a node as the end position of the area represented by the Range object.

Setendafter method: used to specify the end position of a node as the end position of the area represented by the Range object.

Use the following method:

Rangeobj.setstartbefore (node);

Rangeobj.setstartafter (node);

Rangeobj.setendbefore (node);

Rangeobj.setendafter (node);

Let's start with a demo to understand the above four methods, as follows:

<table id= "myTable" border = "1" cellspacing= "0" cellpadding= "0" >
<tr>
<td> first Row first column </td>
<td> first row, second column </td>
</tr>
<tr>
<td> second row first column </td>
<td> second row, second column </td>
</tr>
</table>
<button onclick= "Deletefirstrow ()" > Delete First line </button>

The JS code looks like this:

<script>
function Deletefirstrow () {
var myTable = document.getElementById ("myTable");
if (MyTable.rows.length > 0) {
var row = mytable.rows[0];
var rangeobj = Document.createrange ();
Rangeobj.setstartbefore (row);
Rangeobj.setendafter (row);
Rangeobj.deletecontents ();
}
}
</script>

As shown in the code above, the first row of the table will be deleted when the user clicks the Delete first line button;

Clonerange Method The Clonerange method of the Range object is used to copy the current Range object, which returns the copied Range object, using the following example:

var rangeclone = Rangeobj.clonerange ();

Let's take a look at a demo example, as follows:

The JS code is as follows:

<script>
function Clonearange () {
var testobj = document.getElementById ("test");
var rangeobj = Document.createrange ();
Rangeobj.selectnodecontents (Testobj);
var rangeclone = Rangeobj.clonerange ();
alert (Rangeclone);
}
</script>

As shown in the following:

clonecontents method This method is used to append an HTML code to the page and to clone the HTML code in the area represented by the Range object into the appended HTML code;

Use the following method:

var html = rangeobj.clonecontents ();

The method does not use any parameters, and the method returns a DocumentFragment object, which is a container element that becomes very useful when it is necessary to append, delete, modify, or find elements on the page;

As shown in the following code:

<div id= "div" >     instance text     <br/>    <button onclick= "clonedivcontent ()" > Clone </button> </div>

The JS code is as follows:

<script>
function Clonedivcontent () {
var div = document.getElementById ("div");
var rangeobj = Document.createrange ();
Rangeobj.selectnodecontents (DIV);
var documentfragment = rangeobj.clonecontents ();
Div.appendchild (DocumentFragment);
}
</script>

As in the code, when the user clicks the Clone button on the page, the contents of the DIV element will be cloned to the bottom of the div element; Let's look at the properties of the DocumentFragment object as follows:

extractcontents The DocumentFragment method is used to clone the HTML code in the area represented by the Range object into a single object, and then remove the HTML code from the page;

This method is used in the following ways:

var documentfragment = rangeobj.extractcontents ();

The method returns a DocumentFragment object that contains the HTML code in the range represented by the Range object.

As shown in the following code:

<div id= "Srcdiv" style= "width:300px;height:50px;" >demo</div><div id= "Destdiv" style= "Width:300px;height:50px;background:blue;" >demo2</div><button onclick = "movecontent ()" > moving element content </button>

The JS code is as follows:

<script>
function Movecontent () {
var srcdiv = document.getElementById ("Srcdiv");
var destdiv = document.getElementById ("Destdiv");
var rangeobj = Document.createrange ();
Rangeobj.selectnodecontents (SRCDIV);
var documentfragment = rangeobj.extractcontents ();
Destdiv.appendchild (DocumentFragment);
}
</script>

The original page is as follows:

Click the button to change to the following:

Insertnode Method: This method is used to insert the specified node into the area represented by a Range object, where the insertion position is the starting point of the area represented by the Range object, and if the node already exists on the page, the node is moved to the beginning of the area represented by the Range object. Here's how to use it:

Rangeobj.insertnode (node);

The following demo:

The code is as follows:

<div onmouseup= "Movebutton ()" style= "width:400px;height:100px;" >>aaaaaaaaabbbbbb</div><button id= "button" > button </button>

The JS code is as follows:

<script> function Movebutton () {var button = document.getElementById ("button");        var selection = Document.getselection ();            if (Selection.rangecount > 0) {var range = selection.getrangeat (0);        Range.insertnode (button); }}</script>

The page is initialized as follows:

When you press the key in the appropriate place, it becomes the following:

Original address: http://www.alixixi.com/web/a/2015070495006.shtml

Related content:

JS Range HTML Document/text content selection, library and application description: http://www.zhangxinxu.com/wordpress/?p=1591

A study of Range objects in HTML5 (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.