This article describes the way JavaScript lets textarea support the TAB key. Share to everyone for your reference. The implementation method is as follows:
HTMLTextAreaElement.prototype.getCaretPosition = function () {//return The caret position of the textarea return THIS.S
Electionstart;
}; HTMLTextAreaElement.prototype.setCaretPosition = function (position) {//change caret position of textarea
Electionstart = position;
This.selectionend = position;
This.focus ();
}; HTMLTextAreaElement.prototype.hasSelection = function () {//if the TEXTAREA has selection then return True if (This.sele
Ctionstart = = This.selectionend) {return false;
else {return true;
}
}; HTMLTextAreaElement.prototype.getSelectedText = function () {//return The selection text return this.value.substring (th
Is.selectionstart, This.selectionend);
}; HTMLTextAreaElement.prototype.setSelection = function (start, end) {//change the selection area of the textarea This.sel
Ectionstart = 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 () + "". Length; 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.GETCARETP
Osition ()) = = "") {//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 = =) {//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 = =) {//right arrow var newcaretposition;
if (Textarea.value.substring (textarea.getcaretposition () + 4, textarea.getcaretposition ()) = = "") {//it ' s tab space
Newcaretposition = textarea.getcaretposition () + 3;
Textarea.setcaretposition (newcaretposition);
}
}
}
The
wants this article to help you with your JavaScript programming.