TextRange is an object used to express text in HTML elements. Although we do not usually use this object, it is provided in IE4.0. However, the call methods provided by TextRange are obscure, so what can we do with it?
The traditional use of TextRange is to circle text content on web pages, such as changes, deletions, and additions. However, its classic purpose is to search for text on the Web page (which is relatively simple) and obtain the cursor position of the input box. The latter can be used to derive many more useful functions. For example, to restrict the input of MaskTextBox, the core technical point is to obtain the cursor position of the input box, and then use a regular expression to judge the input content. In addition, I will introduce "natural navigation using arrow keys in the input box matrix". The core technical point is to obtain the cursor position in the input box.
The entire code for getting the cursor position in the input box is actually very short, but these objects and methods are not very commonly used.
<Script language = "javascript">
Function GetCursorPsn (txb)
{
Var slct = document. selection;
Var rng = slct. createRange ();
Txb. select ();
Rng. setEndPoint ("StartToStart", slct. createRange ());
Var psn = rng. text. length;
Rng. collapse (false );
Rng. select ();
Return psn;
}
</Script>
To thoroughly understand the usage of TextRange, please refer to MSDN for details about TextRange.
The following describes the side effects of using the GetCursorPsn () method in the input box. For the input box <input type = "text" onkeydown = "GetCursorPsn (this)">, it cannot use the Shift + left and right arrow keys to select text; for <textarea onkeydown = "GetCursorPsn (this)"> </textarea>, you cannot use Shift + up, down, and left arrow keys to select text. Because the Code calls rng. collapse (false) after obtaining the current cursor to the startPoint of the text, it will change the EditPoint of the text in the text basket. However, this side effect basically won't cause any big problems for us to use the text box, so we don't have to worry too much about it.