How to handle in textarea?

前端 未结 6 1406
青春惊慌失措
青春惊慌失措 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:11

    Good god, all previous answers failed to provide the commonly decent (i.e. for programmers) tab control.

    That is, a hitting TAB on selection of lines will indent those lines, and SHIFTTAB will un-indent them.

    _edited (Nov 2016): keyCode replaced with charCode || keyCode, per KeyboardEvent.charCode - Web APIs | MDN

    (function($) {
      $.fn.enableSmartTab = function() {
        var $this;
        $this = $(this);
        $this.keydown(function(e) {
          var after, before, end, lastNewLine, changeLength, re, replace, selection, start, val;
          if ((e.charCode === 9 || e.keyCode === 9) && !e.altKey && !e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            start = this.selectionStart;
            end = this.selectionEnd;
            val = $this.val();
            before = val.substring(0, start);
            after = val.substring(end);
            replace = true;
            if (start !== end) {
              selection = val.substring(start, end);
              if (~selection.indexOf('\n')) {
                replace = false;
                changeLength = 0;
                lastNewLine = before.lastIndexOf('\n');
                if (!~lastNewLine) {
                  selection = before + selection;
                  changeLength = before.length;
                  before = '';
                } else {
                  selection = before.substring(lastNewLine) + selection;
                  changeLength = before.length - lastNewLine;
                  before = before.substring(0, lastNewLine);
                }
                if (e.shiftKey) {
                  re = /(\n|^)(\t|[ ]{1,8})/g;
                  if (selection.match(re)) {
                    start--;
                    changeLength--;
                  }
                  selection = selection.replace(re, '$1');
                } else {
                  selection = selection.replace(/(\n|^)/g, '$1\t');
                  start++;
                  changeLength++;
                }
                $this.val(before + selection + after);
                this.selectionStart = start;
                this.selectionEnd = start + selection.length - changeLength;
              }
            }
            if (replace && !e.shiftKey) {
              $this.val(before + '\t' + after);
              this.selectionStart = this.selectionEnd = start + 1;
            }
          }
        });
      };
    })(jQuery);
    
    $(function() {
      $("textarea").enableSmartTab();
    })
    
    

提交回复
热议问题