Research on the Range object in HTML5, html5range

Source: Internet
Author: User

Research on the Range object in HTML5 (reprinted), html5range

I. Concept of a Range object

The Range object represents a continuous area on the page. You can use the Range object to obtain or modify any area on the page. You can create an empty Range object as follows:

Var range = document. createRange ();

In html5, Each browser window and each window has a selection object, representing the area selected by the user's mouse on the page ,(Note: IE9 has been testedThe following browsers do not support SelectionObject), You can use the following statement to create a selection object;

Var selection = document. getSelection ();Or

Var selection = window. getSelection ();

Each selection object has one or more Range objects. Each range object represents a continuous area in the Range selected by the user's mouse. In firefox, you can use the ctrl key to select multiple consecutive regions. Therefore, in firefox, a selection object has multiple range objects. In other browsers, you can select only one consecutive region, therefore, there is only one range object.

You can use the getRangeAt method of the selection object to obtain a Range object of the selection object, as follows:

Var range = document. getSelection (). getRangeAt (index );

The getRangeAt method has an index parameter that represents the serial number of the Range object. We can use the value of the rangeCount parameter of the Selection object to determine whether the user has selected the content;

Test the Code as follows:

<H3> examples of selection and range objects <Input type = "button" value = "click" 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 selected" + selection. rangeCount + "segment content <br/>"; for (var I = 0; I <selection. rangeCount; I ++) {var range = selection. getRangeAt (I); html + = "section" + (I + 1) + "content:" + range + "<br/>";} showRangeDiv. innerHTML = html ;}}</script>

As shown in the preceding Code, after you select a text segment, click the button to display the selected text, as shown in the following figure:

In chrome:

Ii. attributes and methods of the Range object

The attributes are as follows:

Collapsed (boolean): used to determine whether the start point and end point of the region represented by the Range object are in the same position. If the value is the same, true is returned;

CommonAncestorContainer (node): return the node where the region represented by the Range object is located. The attribute value is the lowest layer node that contains the region (a node may be an element, or a complete text.

EndContainer (node): Used to return the node where the destination of the region represented by the Range object is located. The attribute value is the lowest-level node that contains the destination of the region.

EndOffset (integer type): returns the distance between the end point of the region represented by the Range object and the start point of the node containing the end point.

StartContainer (node): return the node where the starting point of the region represented by the Range object is located. The attribute value is the lowest-level node that contains the starting point of the region.

StartOffset (integer type): returns the distance between the start point of the region represented by the Range object and the start point of the node containing the start point.

There are still many methods below, and the meaning of the methods is hard to understand. I also see this in the book. By the way, I made a demo and tried it to understand its meaning. You can take a look at what you need to use later;

SelectNode method: The selectNode method of the Range object is used to specify the start point of a Range object as the start point of a node and the end point of a Range object as the end point of the node, make the region represented by the Range object contain the node. The usage is as follows:

RangeObj. selectNode (node );

The rangeObj above represents a Range object. This method uses a parameter to represent a node on the page.

SelectNodeContents: This method is used to specify the start point of a Range object as the start point of all content in a node, and specify the end point of the Range object as the end point of all content of the node, make the area represented by the Range object contain all the content of the node. The usage is as follows:

RangeObj. selectNodeContents (node );

The meaning is shown above;

DeleteContents method: Used to delete the content contained in the Range object from the page. The method is as follows:

RangeObj. deleteContents ();

The following is a demo to understand the above three methods:

<Div id = "div"> <script> function deleteRangeContents (flag) {var div = document. getElementById ("div"); var rangeObj = document. createRange (); if (flag) {// selectNodeContents indicates that all content in the selected Range object is deleted from rangeObj. selectNodeContents (div); rangeObj. deleteContents ();} else {rangeObj. selectNode (div); rangeObj. deleteContents () ;}}</script>

When the code executes document. createRange ();, let's see what the value of the rangeObj object is,

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

When the code is executed below, the value of the rangeObj object is changed to the following:

When we click the delete element button, It is shown as follows:

The rangeObj object becomes as follows:

SetStartMethodIt is used to specify a position in a node as the starting position of the region represented by the Range object. The usage is as follows:

RangeObj. setStart (node, curIndex );

The preceding Code rangeObj represents a Range object. The setStart method uses two parameters. The first parameter node represents a node, and the second parameter is a number, when the first parameter node represents a text node with a text content, this parameter is used to specify the end position of the text as the starting position of the region represented by the Range object. When the node represented by the first parameter contains other subnodes, this parameter is used to specify the end position of the subnodes as the starting position of the region represented by the Range object;

SetEndMethodSpecifies the end position of the region represented by the Range object at a certain position in a node. The usage is as follows:

RangeObj. setEnd (node, curIndex );

The meanings of the two parameters in this method are the same as those in the setStart method, except that one is the start position and the other is the end position;

Let's take a look at a demo to understand the meaning of the above two methods. The Code is as follows:

<Div id = "myDiv"> the third to tenth characters in the text will be deleted </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, 3rd to 10th words are deleted ~

SetStartBeforeMethod:Specifies the start position of a node as the starting position of the region represented by the Range object.

SetStartAfterMethod:Specifies the end point of a node as the starting point of the region represented by the Range object.

SetEndBeforeMethod:Specifies the start position of a node as the end position of the region represented by the Range object.

SetEndAfterMethod:Specifies the end point of a node as the end point of the region represented by the Range object.

The usage is as follows:

RangeObj. setStartBefore (node );

RangeObj. setStartAfter (node );

RangeObj. setEndBefore (node );

RangeObj. setEndAfter (node );

Let's make a demo to understand the above four methods:

<Table id = "myTable" border = "1" cellspacing = "0" cellpadding = "0">
<Tr>
<Td> first column of the First row </td>
<Td> second column of the First row </td>
</Tr>
<Tr>
<Td> first column of the Second row </td>
<Td> second column of the Second row </td>
</Tr>
</Table>
<Button onclick = "deleteFirstRow ()"> Delete the first row </button>

The JS Code is as follows:

<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 preceding code, When you click the Delete row button, the first row of the table is deleted;

CloneRangeMethodThe cloneRange method of the Range object is used to copy the current Range object. This method returns the copied Range object. The method is as follows:

Var rangeClone = rangeObj. cloneRange ();

Let's take a look at a demo column, as shown below:

<Div id = "test"> aaaa </div> <button onclick = "cloneARange ()"> clone a Range object </button>

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:

CloneContentsMethodThis method is used to append an HTML code to the page, and clone the HTML code in the area represented by the Range object to the html code to be appended;

The usage is as follows:

Var html = rangeObj. cloneContents ();

This method does not use any parameters. This method returns a DocumentFragment object, which is a container element. When you need to append, delete, modify, or search for elements on the page, this object becomes very useful;

The following code is used:

<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 shown in the above Code, after you click the clone button on the page, the content of the div element is cloned to the bottom of the div element. Let's take a look at the attributes of the documentFragment object as follows:

ExtractContentsMethodIt is used to clone the html code in the area represented by the Range object to a DocumentFragment object, and then delete the HTML code from the page;

This method is used as follows:

Var documentFragment = rangeObj. extractContents ();

This method returns a DocumentFragment object that contains the HTML code in the area represented by the Range object.

The following code is used:

<div id="srcDiv"><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:

InsertNodeMethod:This method is used to insert a specified node to the region represented by a Range object. The inserted position is the starting position of the region represented by the Range object. If the node already exists on the page, the node will be moved to the starting point of the region represented by the Range object. The usage is as follows:

RangeObj. insertNode (node );

The demo is as follows:

The Code is as follows:

<div onmouseup="MoveButton()"><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 the key is pressed in the corresponding place, it becomes as follows:

Address: http://www.alixixi.com/web/a/2015070495006.shtml

Related content:

JS Range HTML document/Text Content Selection, library and application: http://www.zhangxinxu.com/wordpress? P = 1591

Related Article

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.