Textarea 和 tab 键:获取 \t 而不是跳转到下一个元素

Textarea and tab keys: Get \t instead of jumping to the next element

我正在使用一个名为 userInput 的 html 文本区域,但每当我按下 Tab 键时,它就会移动到下一个元素。我如何让制表键创建一个制表符或至少一些空格,而不是移动到下一个元素?

为 keydown 事件添加一个事件侦听器,如果它是一个已被按下的选项卡,则阻止该事件:

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>