This example describes the way JavaScript lets textarea support the TAB key. Share to everyone for your reference. The implementation methods are as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65-66 |
HTMLTextAreaElement.prototype.getCaretPosition = function () {//return The caret position of the textarea return this.se Lectionstart; }; HTMLTextAreaElement.prototype.setCaretPosition = function (position) {//change caret position of textarea Lectionstart = position; This.selectionend = position; This.focus (); }; HTMLTextAreaElement.prototype.hasSelection = function () {//if the TEXTAREA has selection then return True if (This.selec Tionstart = = This.selectionend) {return false;} else {return true;}}; HTMLTextAreaElement.prototype.getSelectedText = function () {//return The selection text return this.value.substring ( This.selectionstart, This.selectionend); }; HTMLTextAreaElement.prototype.setSelection = function (start, end) {//change the selection area of the textarea This.sele Ctionstart = start; This.selectionend = end; This.focus (); }; var textarea = document.getElementsByTagName (' textarea ') [0]; Textarea.onkeydown = function (event) {//support tab on TextareA if (Event.keycode = = 9) {//tab was pressed var newcaretposition; newcaretposition = textarea.getcaretposition () + "". L Ength; Textarea.value = textarea.value.substring (0, Textarea.getcaretposition ()) + "" + textarea.value.substring ( Textarea.getcaretposition (), textarea.value.length); Textarea.setcaretposition (newcaretposition); return false; } if (Event.keycode = = 8) {//backspace if textarea.value.substring (Textarea.getcaretposition ()-4, Textarea.getcaretposition ()) = = "") {//it ' s tab space Var newcaretposition; Newcaretposition = Textarea.getcaretposition ()-3; Textarea.value = textarea.value.substring (0, Textarea.getcaretposition ()-3) + textarea.value.substring ( Textarea.getcaretposition (), textarea.value.length); Textarea.setcaretposition (newcaretposition); } if (Event.keycode = n) {//left arrow var newcaretposition; if (textarea.value.substring textarea.getcaretposition () -4, textarea.getcaretposition () = = "") {//it ' s a tab space newcaretposition = TEXTAREA.GETCARetposition ()-3; Textarea.setcaretposition (newcaretposition); } if (Event.keycode = n) {//right arrow var newcaretposition; if (textarea.value.substring textarea.getcaretposition ( + 4, textarea.getcaretposition ()) = = "") {//it ' s a tab space newcaretposition = textarea.getcaretposition () + 3; Textarea.setcaretposition (newcaretposition); } } } |
The
wants this article to help you with your JavaScript programming.