代码之家  ›  专栏  ›  技术社区  ›  Kevin K

text区域和选项卡键:获取而不是跳转到下一个元素

  •  2
  • Kevin K  · 技术社区  · 7 年前

    我正在使用一个名为 userInput

    1 回复  |  直到 7 年前
        1
  •  2
  •   ibrahim mahrir    7 年前

    var ta = document.getElementById("ta");
    
    ta.addEventListener("keydown", function(e) {                           // when a keydown happens
      if(e.keyCode === 9) {                                                // if the key that is pressed is a tab (keyCode 9)
        var start = this.selectionStart,                                   // get the selection start (or the cursor position if nothing is selected)
            end = this.selectionEnd,                                       // get the selection end (or the cursor position if nothing is selected)
            value = this.value;
        this.value = value.substr(0, start) + "\t" + value.substr(end);    // add a tab in-between instead of the selected text (or at cursor position if nothing is selected)
        this.selectionStart = this.selectionEnd = start + 1;               // set the cursor to one character after the last start index (right after the newly added tab character)
        e.preventDefault();                                                // IMPORTANT: prevent the default behavior of this event (jumps to the next element and give it focus)
      }
    })
    #ta {
      width: 100%;
      height: 170px;
    }
    <textarea id="ta"></textarea>