(1) Get the starting point of the selected area of Textarea or the input cursor position when there is no selection
Non-IE browsers, such as firefox and chrome, support selectionStart to get the starting point of the selected area, but IE browser does not To support this attribute, it needs to be obtained indirectly through TextRange. This can be achieved by using the compareEndPoints method of the TextRange object to compare the starting point.
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 start point
for ( var sel_start = 0 ; range_textarea .compareEndPoints('StartToStart' , range) < 0; sel_start )
range_textarea .moveStart( 'character', 1);
start = sel_start;
} // else
return start;
}
But something to note is that under chrome, if the textarea is set to readonley, the input cursor will not appear in the textarea, and the returned selectionStart and selectionEnd are both 0 It is normal under .firefox.
(2) Set the selected area in Textarea
Similarly, non-IE browsers support the setSelectionRange method to specify the selected character range, but IE does not support it, and it is also done through TextRange Operation, what needs to be paid attention to here is the relative position of the selected interval of Textarea under IE. For example, the following code first movesStart and moveEnd sets both the starting point and the end point to 0. After the collapse move takes effect, the starting point remains unchanged. First moveEnd moves the end point of the moving interval, and then moveStart moves the starting point of the interval. Before the starting point is changed, it can be guaranteed The relative position remains unchanged, which is easier to understand.
/**
* 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 starting point to 0
range.moveStart( "character", 0)
range.moveEnd( "character", 0);
range.collapse( true); // Move the insertion 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 implementing the selected area acquisition and setting methods, other implementations such as text insertion and replacement will be relatively simple.