如何处理textarea中的<tab>?</tab>

时间:2011-05-26 14:54:17

标签: javascript jquery html

我想要一个textarea来处理按 tab 键的情况。

默认情况下,如果按选项卡键,则焦点将离开textarea。但是当用户想要在textarea中键入 tab 键时呢?

我可以捕获此事件并将焦点返回到textarea并将标签添加到当前光标位置吗?

6 个答案:

答案 0 :(得分:130)

您可以:http://jsfiddle.net/sdDVf/8/


$("textarea").keydown(function(e) {
    if(e.keyCode === 9) { // tab was pressed
        // get caret position/selection
        var start = this.selectionStart;
        var end = this.selectionEnd;

        var $this = $(this);
        var value = $this.val();

        // set textarea value to: text before caret + tab + text after caret
        $this.val(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();
    }
});

答案 1 :(得分:27)

以下是pimvdb答案的修改版本,不需要JQuery:

document.querySelector("textarea").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);

我在Firefox 21.0和Chrome 27中进行了测试。不知道它是否适用于其他任何地方。

答案 2 :(得分:12)

天哪,所有以前的答案都无法提供通常不错的(即程序员)标签控件。

也就是说,在选择行时点击 TAB 将缩进这些行, SHIFT TAB 将取消缩进它们。

_edited(2016年11月):keyCode替换为charCode || keyCode,每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();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="80">
/* Just some code to edit with our new superTab */
(function($) {
    $.fn.enableSmartTab = function() {
        $this = $(this);
        $this.keydown(function(e) {
            if ((e.charCode === 9 || e.keyCode === 9) && !e.metaKey && !e.ctrlKey && !e.altKey) {
                e.preventDefault();
            }
        }
    }
}
</textarea>

答案 3 :(得分:5)

在Vanilla(默认)JS中,这将是:

&#13;
&#13;
function auto_delete_emails() {

  var label = GmailApp.getUserLabelByName("foo");
  var sender = "\"Foo Bar\" <info@foo.bar>";

  if (label != null) {
    var delayDays = 30
    var maxDate = new Date();

    maxDate.setDate(maxDate.getDate() - delayDays);

    var threads = label.getThreads();
    for (var i = 0; i < threads.length; i++) {
      var messages = GmailApp.getMessagesForThread(threads[i]);
      var from = messages[0].getFrom();
      if (from == sender) {
        if (threads[i].getLastMessageDate < maxDate) {
          threads[i].moveToTrash();
        }
      }
    }
  }
}
&#13;
products {id, subcategory_id}
subcategories {id, category_id}
category {id, name}


Product Model:
public function subcategory(){
    return $this->belongsTo('App\Subcategory', 'subcategory_id');
}


Subcategory Model:
public function product(){
    return $this->hasMany('App\Product', 'subcategory_id');
}
public function category(){
    return $this->belongsTo('App\Category');
}


Category Model:
public function subCategory(){
    return $this->hasMany('App\Subcategory');
}

public function product(){
   return $this->hasManyThrough('App\Product', 'App\Subcategory');
}
&#13;
  var textareas = document.getElementsByTagName('textarea');

  if ( textareas ) {
    for ( var i = 0; i < textareas.length; i++ ) {
      textareas[i].addEventListener( 'keydown', function ( e ) {
      if ( e.which != 9 ) return;

      var start 			= this.selectionStart;
      var end				  = this.selectionEnd;

      this.value 			= this.value.substr( 0, start ) + "\t" + this.value.substr( end );
      this.selectionStart = this.selectionEnd = start + 1;

      e.preventDefault();
      return false;
      });
    }
  }
&#13;
&#13;
&#13;

答案 4 :(得分:0)

在搜索谷歌时发现这一点。我做了一个非常短的,也可以缩进和反转缩进文本选择:

    jQ(document).on('keydown', 'textarea', function(e) {
        if (e.keyCode !== 9) return;
        var Z;
        var S = this.selectionStart;
        var E = Z = this.selectionEnd;
        var A = this.value.slice(S, E);
        A = A.split('\n');
        if (!e.shiftKey)
            for (var x in A) {
                A[x] = '\t' + A[x];
                Z++;
            }
        else
            for (var x in A) {
                if (A[x][0] == '\t')
                    A[x] = A[x].substr(1);
                Z--;
            }
        A = A.join('\n');
        this.value = this.value.slice(0, S) + A + this.value.slice(E);
        this.selectionStart = S != E ? S : Z;;
        this.selectionEnd = Z;
        e.preventDefault();
    });

答案 5 :(得分:0)

启用内部(多个)textarea元素的标签

更正@alexwells答案并启用现场演示

&#13;
&#13;
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);
    }
&#13;
<textarea rows="10" cols="80"></textarea>
   <textarea rows="10" cols="80"></textarea>
&#13;
&#13;
&#13;