Keypress in jQuery: Press TAB inside TEXTAREA (when editing an existing text)

前端 未结 4 431
一个人的身影
一个人的身影 2020-12-30 12:47

I want to insert TAB characters inside a TEXTAREA, like this:


I can

4条回答
  •  粉色の甜心
    2020-12-30 13:18

    I was creating a AJAX powered simple IDE for myself so I can rapidly test out PHP snippets.

    I remember stumbling upon the same problem, here's how I solved it:

    $('#input').keypress(function (e) {
        if (e.keyCode == 9) {
            var myValue = "\t";
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos,this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
    
            e.preventDefault();
        }
    });
    

    #input is the ID of the textarea.

    The code is not completely mine, I found it on Google somewhere.

    I've only tested it on FF 3.5 and IE7. It does not work on IE7 sadly.

提交回复
热议问题