This article illustrates the method of indenting the TAB key in JavaScript implementation textarea. Share to everyone for your reference. Specifically as follows:
Online search for some of the relevant solutions, other uses two or three lines of JavaScript to solve, but there are some small problems. There is also the use of jquery, and very concise.
The JavaScript code in this article implements the ability to enter the TAB key and automatically indent in textarea. However, this code in Google Browser can not be implemented in the normal,
Copy Code code as follows:
Sel =event.srcelement.document.selection.createrange ()
This sentence will be an error:
Ncaught Exception Typeerror:cannot Read Property ' selection ' of undefined
The code executes normally in IE, as follows:
<mce:script type= "Text/javascript" > <!--function edittab () {var code, SEL, TMP, R var tabs= "" Event
. returnvalue = False sel =event.srcelement.document.selection.createrange () R = Event.srcElement.createTextRange () Switch (event.keycode) {case (8): if (!) ( Sel.getclientrects (). length > 1)) {Event.returnvalue = true return} code = SEL
. text TMP = Sel.duplicate () tmp.movetopoint (R.getboundingclientrect (). Left, Sel.getclientrects () [0].top) Sel.setendpoint ("Starttostart", tmp) Sel.text = Sel.text.replace (/^/t/gm, "") code = Code.replace (/^/t/g M, ""). Replace (//r/n/g, "/R") R.findtext (Code) R.select () break case (9): if (SEL.GETCL Ientrects (). length > 1) {code = Sel.text tmp = sel.duplicate () tmp.movetopoint (r.get Boundingclientrect (). Left, Sel.getclientrects () [0].top) Sel.setendpoint ("StarTtostart ", tmp" Sel.text = "/t" +sel.text.replace (//r/n/g, "/r/t") code = code.replace (//r/n/g, "/r/t")
R.findtext (Code) R.select () else {sel.text = '/t ' Sel.select () Break Case (a): TMP = Sel.duplicate () tmp.movetopoint (R.getboundingclientrect (). Left , Sel.getclientrects () [0].top) Tmp.setendpoint ("Endtoend", sel) for (var i=0; Tmp.text.match (/^[/t]+/g) ;& I<tmp.text.match (/^[/t]+/g) [0].length; i++) Tabs + = "/t" Sel.text = "/r/n" +tabs sel.select () Break Default:event.returnValu E = True Break}}//--> </mce:script>
When used:
Copy Code code as follows:
<textarea cols=80 rows=20 name= "input" onkeydown= "Edittab ()" ></textarea>
I hope this article will help you with your JavaScript programming.