Joke Collection Website - Talk about mood - The difference between selection and range objects
The difference between selection and range objects
Operating text selection is a very troublesome thing, because the text mode of HTML itself is not suitable for text selection. But since there is a functional requirement, we have to bite the bullet and do it. Currently, there are two standards for implementing text selection. One is the old standard. IE6, 7, and 8 use this old standard and calculate HTML as plain text. This method is easy to operate for plain text, but it is troublesome for rich text. This method operates by reducing HTML to ordinary text, so there are big logical problems. What is more popular now is the new standard, which is basically compatible with non-IE browsers, and IE is compatible starting with IE9. The new standard operation method is to operate the text accurately to the node. This method is much more logical than the old standard method of destroying HTML, and this method is easier to operate on rich text. Text selections are called TextRange objects in the old standard and Range objects in the new standard. They are Selection-based objects. Now, let's first talk about the old standard text selection operation method.
Since it is based on the Selection object, we must first obtain the Selection object. It is in the document object. You can find it directly using document.selection. It provides the createRange method, which can create a TextRange object. (There is more than one way to create a TextRange object, and other methods will not be introduced in this article.) After getting the TextRange object, you can operate the selection. Look at the code below
div {width:600px;border:1px solid red;}
< p> A gold bottle of sake is worth ten thousand dollars, and a jade plate of delicacies is worth ten thousand dollars.
Stopping the cup and throwing chopsticks, I can't eat. I draw my sword and look around at a loss.
If you want to cross the Yellow River, which is blocked by ice, you will have to climb the snow-covered mountains of Taihang.
I was fishing on the Bixi River in my spare time, and suddenly I was riding a boat and dreaming of the sun.
Traveling is difficult! Traveling is difficult! There are many different roads, where are you now?
There will be times when the wind blows and the waves break, and the clouds and sails are hung directly to help the sea.
//Variable initialization
var range,editor; p>
range=document.selection.createRange();
editor=document.getElementById("editor");
//Select all text in editor
p>range.moveToElementText(editor);
//Abandon the end position of the selection
range.collapse();
//Change the current Move the end position of the selection backward 16 characters
range.moveEnd("character",16);
//Select this selection on the interface
range.select();
After reading this code, you should understand how to select a text selection. It is worth mentioning here that the collapse method discards the end position and is not simply set to the start position. After the end position is discarded, it will always be equal to the start position as long as it is not reset.
Even if you modify the start position, the end position will still be at the modified start position. Next, look at the code. For convenience, I will only write the JS part of the next code, and the HTML part is the same as in the first example. //Variable initialization
var range,editor;
range=document.selection.createRange();
editor=document.getElementById("editor") ;
//Select all text in the editor
range.moveToElementText(editor);
//Discard the end position of the selection
range.collapse();
//Move the starting position of the current selection backward 17 characters
range.moveStart("character",17);
//Move the end position of the current selection backward 16 characters
range.moveEnd("character",16);
//Select this selection on the interface
range.select(); This code will select the second row. You will find that the second parameter of moveEnd is 16 instead of 17+16. This is what it said above that after discarding the end position it will be the same as the start position before redefining it. That’s about it for setting the position, and then getting the position of a text selection. In fact, this operation is not necessary. If you want to save the position of a text selection, just save the TextRange object directly. There is no need to be precise to the number of characters. . However, for some strange needs, I will introduce here the method of obtaining the location information of the constituency. Obtaining this information is not as easy as selecting the position. You need to use a method called setEndPoint. Since the TextRange object cannot directly obtain the value, the setEndPoint method can only be used to assign the start or end position of one TextRange object to another TextRange object, so that we can calculate the precise position by calculating the number of words. As for the specific usage of setEndPoint, you can refer to the link at the end of this article to see the official instructions. Below is the code to get the location of the selection.
//Get the editor object
var editor=document.getElementById("editor");
//Mouse event
document.onmouseup=function(){
//Variable declaration
var st,cr,l,r;
//Create a text selection and Set the cursor to the beginning of the editor
st=document.selection.createRange();
st.moveToElementText(editor);
st.collapse( );
//Create a selection object (the current area will be selected by default)
cr=document.selection.createRange();
//Put st end is set to start of cr
st.setEndPoint("EndToStart",cr);
//The starting position is the text length of st
l= st.text.length
//The end position is the starting position plus the text length of the interval
r=l+cr.text.length
// Output location information
alert("Start position: "+l+"\n"+"End position: "+r);
}; Knowing the above, in lower versions There should be basically no problem operating text selections in the browser. Next, let’s talk about the Range object of the new browser.
The first is the Selection object. It is not a document property like the old standard. You must use the getSelection method to obtain it. This method is on the window object, so we can use it directly. . The new standard Range object is very different from the old standard. It is not created from the Selection object, but from the document object. You can use document.createRange to create a new selection. The Selection object of the new standard is also very different from the old standard. It is not so much a difference as it is two completely different concepts. The new standard Selection object can contain multiple Range objects at the same time. Use the getRangeAt method to get the specific object. The parameter is the subscript of the Range object group. Next, let’s implement the function of selecting the second line of text. Look at the code
//Variable initialization
var editor,selection,range,s;
editor=document.getElementById("editor");
s=editor.childNodes;
selection=getSelection();
range=document.createRange();
//Set range Start and end points
range.setStart(s[2],0);
range.setEnd(s[3],0);
/ /Remove all the original ranges in the selection
selection.removeAllRanges();
//Add this new range to the selection
selection.addRange (range); If you look at the code of the new standard through the eyes of the old standard, you will definitely be confused. The standard Range object can be said to be very, very precise, so precise that it will drive you crazy. It is accurate to the first character of the text node, and also includes whitespace characters.
Therefore, the Range object is very laborious to calculate, but its logic is very complete and does not destroy the original format of HTML at all. Unlike the old standard TextRange object, all HTML tags are abandoned for the convenience of calculation. Perhaps the most difficult thing to understand about the above code is where the start and end positions are set. Both the setStart and setEnd methods have two parameters. The first parameter is the node, and the second parameter has two meanings. If the first parameter is a text node, then the second parameter is the position of the text. If it is not a text node, then the second parameter is the position of its child node. It's a bit hard to describe in words, but if you don't think about it carefully enough, you should be able to understand. s[2] in the above code is the third child node of the editor (the first subscript is 0). If you use Chrome's debugging tool to look at it, you will find that the third child node is the text node of the second line. , the following parameter is 0, indicating the first character in this text node. The following s[3] is similar, except that it points to the BR label. There is no text or child nodes in BR, so setEnd(s[3],0) sets the end position to the position of BR itself. The other codes can be understood from the comments, so I won’t go into details. Next, let’s take a look at how to get the character of the node where the cursor is located. The new version of the acquisition code will be much simpler than the old version. Since there are objects, I don’t need alert output and use conslode.log instead. When debugging, you can press the console to view the information. The following is the code
//Get the selection object
var selection=getSelection();
//Mouse event
document.onmouseup =function(){
console.log("Start Object",selection.anchorNode);
console.log("Start Position",selection.anchorOffset);
console.log("End Object", selection.focusNode);
console.log("End Position", selection.focusOffset);
}; All You can find the data from the selection object without accessing the range. This is a big advantage over the old standard operating methods. There is nothing to say about the above code. The data of the starting point is stored in anchorNode and anchorOffset, and the position of the end point is stored in focusNode and focusOffset. Just remember it.
After learning so much above, the selection operation can be carried out smoothly no matter what browser you use. If you still have any questions, you can ask about the magical conch in the question channel of this site. Below are several documents provided by the official, if you are interested, you can take a look.
- Previous article:(For boys only, personal experience) Tell me about your experience of vomiting when you were sick or caught a cold when you were growing up with a big cold?
- Next article:These seven domestic beers with good reputation have no rice as raw materials. How many "real" beers have you drunk?
- Related articles
- Write beautiful sentences about lovesickness.
- I can't feel other people's sadness. Tell me about it.
- 202 1 is a classic worth collecting: those who don't know love gradually understand, but those who know love dare not stop.
- 64 sentences football
- A collection of 30 sentences suitable for sending on the way to work.
- The epidemic was finally unsealed. Tell me about it.
- What is texture paint? Appreciation of texture paint textures
- Tell me about your own portrait.
- What's the difference between browsing in QQ space and recent visitors?
- Library of "Lü Meng is rushing to fast"