How to handle in textarea?

前端 未结 6 1408
青春惊慌失措
青春惊慌失措 2020-11-27 11:51

I would like a textarea that handles a situation of pressing tab key.

In default case if you press a tab key then focus leaves the textarea. But wh

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 12:06

    Enable tabbing inside (multiple) textarea elements

    Correcting @alexwells answer and enable a live demo

    var textAreaArray = document.querySelectorAll("textarea");
        for (var i = textAreaArray.length-1; i >=0;i--){
            textAreaArray[i].addEventListener('keydown',function(e) {
                if(e.keyCode === 9) { // tab was pressed
                    // get caret position/selection
                    var start = this.selectionStart;
                    var end = this.selectionEnd;
    
                    var target = e.target;
                    var value = target.value;
    
                    // set textarea value to: text before caret + tab + text after caret
                    target.value = value.substring(0, start)
                                + "\t"
                                + value.substring(end);
    
                    // put caret at right position again (add one for the tab)
                    this.selectionStart = this.selectionEnd = start + 1;
    
                    // prevent the focus lose
                    e.preventDefault();
                }
            },false);
        }
    
       

提交回复
热议问题