代码之家  ›  专栏  ›  技术社区  ›  Martin AJ

为什么这个文本区域看起来只添加了一个空格而不是四个?

  •  1
  • Martin AJ  · 技术社区  · 7 年前

    这是我的代码:

    doc.on("keydown", ".textarea_code_snippet", 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();
        }
    });
    

    它处理 制表符 输入 <textarea> .它附加了 \t 当您按下 制表符 钥匙。现在我想加4个空格。这是我的新版本:

    .
    .
     $this.val(value.substring(0, start)
                 + "    "
                 + value.substring(end));
    .
    .
    

    但它只是附加 当我按下时,文本区域的空格 制表符 .我怎样才能修好它?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sebastian Simon SamB    7 年前

    加四个空格。你忘了调整一件事:

    // put caret at right position again (add one for the tab)
    this.selectionStart = this.selectionEnd = start + 1;
    

    您可能只看到插入符号移动一个空格。您需要将以上行更改为:

    // Put caret at right position again (add four for four spaces)
    this.selectionStart = this.selectionEnd = start + 4;