Home > Article > Web Front-end > Javascript implements the indentation processing method of tab key in textarea_javascript skills
The example in this article describes how to implement the indentation processing of tab keys in textarea using JavaScript. Share it with everyone for your reference. The details are as follows:
I searched the Internet for related solutions. Others used two or three lines of javascript to solve the problem, but they all had some minor problems. There is also one that uses JQuery, which is also very simple.
The javascript code in this article implements the function of entering the TAB key in TEXTAREA and automatically indenting it. However, this code cannot be executed normally in Google Chrome. In
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/gm, "").replace(//r/n/g, "/r") r.findText(code) r.select() break case (9) : if (sel.getClientRects().length > 1) { code = sel.text tmp = sel.duplicate() tmp.moveToPoint(r.getBoundingClientRect().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 (13) : 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.returnValue = true break } } // --> </mce:script>
When using:
I hope this article will be helpful to everyone’s JavaScript programming design.