How to use textarea to get cursor position in Javascript
Most people do not understand the knowledge points of this article "how to use textarea to get the cursor location in Javascript", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use textarea to get the cursor location in Javascript" article.
Using Javascript to get the cursor position in textarea
Javascript has always been known for its flexibility and arbitrariness, which makes its function very powerful, and because there is no good debugging tool, it is difficult to use, especially for some beginners. The problem discussed today is to use javascript to get the location of the cursor in textarea. For people who write javascript to write a web editor, getting the cursor location in textarea is a very important issue, and often many people are at a loss in this place and can't find a good way. Yesterday I found a piece of javascript code on the Internet. I didn't want to put the original here, just because it was so wonderful that I was afraid that I would change it, so I'd better put it here.
Varstart=0; varend=0; functionadd () {vartextBox=document.getElementById ("ta"); varpre=textBox.value.substr (0jue start); varpost=textBox.value.substr (end); textBox.value=pre+document.getElementById ("inputtext"). Value+post;} functionsavePos (textBox) {/ / if it is Firefox (1.5), the method is simple if (typeof (textBox.selectionStart) = = "number") {start=textBox.selectionStart; end=textBox.selectionEnd } / / the following is the method of IE (6. 0). It is troublesome to calculate'\ n' elseif (document.selection) {varrange=document.selection.createRange (); if (range.parentElement () .id = = textBox.id) {/ / createaselectionofthewholetextarea varrange_all=document.body.createTextRange (); range_all.moveToElementText (textBox) / / two range, one is the selected text (range), the other is the entire textarea (range_all) / / range_all.compareEndPoints () compares the two endpoints, if range_all is more left than range (furthertotheleft), then / / returns a value less than 0, then the range_all moves a little to the right until the start of the two range is the same. / / calculateselectionstartpointbymovingbeginningofrange_alltobeginningofrange for (start=0;range_all.compareEndPoints ("StartToStart", range)