The first time I heard about the concept of range was at the technical exchange meeting of the spatial editor. At that time, the author told us that the most important concept in the editor was range. By operating range, all operations of the editor can be implemented. What is range? ActuallyThe simple point is the selection area. You may have the concept of a rectangle. In fact, range can be understood as a rectangle.As long as we select a text, the text occupies space, so range has the starting and ending positions.
1. browser compatibility
Currently, there are three similar range objects: W3C range objects, mozzlia selection, and IE textrange.
For the differences between the three, please refer to the document http://www.quirksmode.org/dom/w3c_range.html here for these three are very clear
It can be seen that Mozilla's range is a selection object, and in IE, range is a text range, which is completely different from Mozilla, so we need
Write different compatible scripts respectively. Currently, mainstream browsers Mozilla, chrome safari, and Opera Support selection objects, but opera also supports text range in IE, but not comprehensive.
So the code should be like this
VaR selection; // declare the range object
If (window. getselection ){
// Mainstream browsers, including Mozilla, chrome, and Safari
Selection = Window. getselection ();
} Else if (document. Selection ){
Selection = Document. selection. createRange (); // processing in IE browser. To obtain the content, add the text attribute to the selection object.
}
In fact, we can judge the compatibility of browsers in this way.
If (obj. createTextRange ){
// Operations in IE browser
} Else if (obj. setselectionrange ){
// Non-ie operations
}
I have tracked and downloaded these objects in chrome and IE. Let's take a look.
In IE, if a range object is created
Range. moveend ()
Range. movestart ()
Range. Select ();
You can perform operations on selected text.
In other browsers, you can use obj. setselectionrange () to select an operation. The specific format is as follows:
O. setselectionrange (START, end );
O: text input box object
Start: Start position of the string
End: the end position of the string.
Insert text at the place of the mouse.
You can use document. selection. createRange (). Text = value;
Document. selection. createRange () indicates the textrange object at the current mouse position, and textrange. Text = value indicates inserting a value at the current mouse position.
In other browsers, you can use obj. value = STR + value + str1.
In a non-ie text box, the input OBJ has the selectionstart and selectionend attributes, indicating the current cursor position.
Summary:
1) mentioned that the range object is not created in the same browser, and the content and compatibility of the text are obtained.
2) how to insert text in the text box through the range object
3) how to select text and move the cursor through the range object
You are welcome to make a brick ..