(1) obtain the starting point of the selected area of Textarea or the input cursor position when no selection is made
Non-ie browsers, such as firefox and chrome, support selectionStart to obtain the starting point of the selected region. ie does not support this attribute and needs to be obtained indirectly through TextRange, you can use the compareEndPoints method of the TextRange object to compare the start point.
Copy codeThe Code is as follows:
GetStartPos: function (textarea)
{
If (typeof textarea. selectionStart! = 'Undefined ')
{// Non-IE
Start = textarea. selectionStart;
}
Else
{// IE
Var range = document. selection. createRange ();
Var range_textarea = document. body. createTextRange ();
Range_textarea. moveToElementText (textarea );
// Compare the start point
For (var sel_start = 0; range_textarea. compareEndPoints ('startstart', range) <0; sel_start ++)
Range_textarea. moveStart ('character ', 1 );
Start = sel_start;
} // Else
Return start;
}
However, in chrome, if textarea is set to readonley, the input cursor does not appear in textarea, and the returned selectionStart and selectionEnd values are both 0. firefox.
(2) set the selected region in Textarea
Similarly, non-IE browsers support the setSelectionRange method to specify the range of selected characters, whereas IE does not support it and also uses TextRange, note the relative position of the selected Textarea range in IE. The following code sets moveStart and moveEnd to 0. After the collapse operation takes effect, the start point remains unchanged. First, moveEnd moves the end point of the interval, and then moveStart moves the start point of the interval, before changing the start point, you can ensure that the relative position remains unchanged, making it easier to understand.Copy codeThe Code is as follows:
/**
* Set the selected area of textarea
*/
SetSelectRange: function (textarea, start, end)
{
If (typeof textarea. createTextRange! = 'Undefined') // IE
{
Var range = textarea. createTextRange ();
// First move the relative start point to 0
Range. moveStart ("character", 0)
Range. moveEnd ("character", 0 );
Range. collapse (true); // move the insert cursor to start
Range. moveEnd ("character", end );
Range. moveStart ("character", start );
Range. select ();
} // If
Else if (typeof textarea. setSelectionRange! = 'Undefined ')
{
Textarea. setSelectionRange (start, end );
Textarea. focus ();
} // Else
}
After obtaining and setting the selected region, the replacement implementation is relatively simple, for example, text insertion.