1
我使用的是一個名爲userInput
的html文本區,但每當我按下tab鍵,它就會移動到下一個元素。我如何使tab鍵創建一個選項卡,或者至少是一些空格,而不是移動到下一個元素?Textarea和Tab鍵:獲取 t而不是跳轉到下一個元素
我使用的是一個名爲userInput
的html文本區,但每當我按下tab鍵,它就會移動到下一個元素。我如何使tab鍵創建一個選項卡,或者至少是一些空格,而不是移動到下一個元素?Textarea和Tab鍵:獲取 t而不是跳轉到下一個元素
添加事件偵聽器keydown事件,並防止萬一,如果它是一個標籤that've被按下:
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>