Home > Web Front-end > JS Tutorial > Use TextRange to get the position of the cursor in the input box_javascript skills

Use TextRange to get the position of the cursor in the input box_javascript skills

WBOY
Release: 2016-05-16 19:25:21
Original
1206 people have browsed it

TextRange is an object used to represent text in HTML elements. Although we don't often use this object, it is already provided in IE4.0. However, the calling methods provided by TextRange are relatively obscure, so what can we do with it?

The traditional use of TextRange is to operate the text content that the user circles with the mouse on the Web page, such as changing, deleting, adding, etc. But its classic use is to find text in a Web page (this is relatively simple) and get the position of the input box cursor. The latter can derive many more useful uses, such as the MaskTextBox that limits input. Its core technical point is to obtain the cursor position of the input box, and then use regular expressions to determine the input content. There is also "natural navigation in the input box matrix using the arrow keys" that I will introduce later. The core technical point is to obtain the cursor position in the input box.

The entire code to obtain the cursor position in the input box is actually very short, but these objects and methods are not commonly used.


To thoroughly understand the specific usage of TextRange, you need to know some related content, please refer to MSDN
. Here we talk about the side effects of using the GetCursorPsn() method on input box operations. For the input box
, it will no longer be possible to use the Shift up, down, left and right arrow keys to select text. Because after the code obtains the startPoint of the current cursor to the text, calling rng.collapse(false); will change the EditPoint of the text in the text box. However, this side effect will basically not cause any major problems for us when using text boxes, so we basically don’t need to pay too much attention to it. <script> <BR>function GetCursorPsn(txb) <BR>{ <BR> var slct = document.selection; <BR> var rng = slct.createRange(); <BR> txb.select(); <BR> rng.setEndPoint("StartToStart", slct.createRange()); <BR> var psn = rng.text.length; <BR> rng.collapse(false); <BR> rng.select(); <BR> return psn; <BR>} <BR></script>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template