2017-09-16 51 views

回答

1

添加事件偵聽器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>

相關問題