问题
Here is my code:
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();
}
});
It handles Tab key in the <textarea>. It appends \t to the textarea when you press the Tab key. Now I want to add 4 spaces instead. Here is my new version:
.
.
$this.val(value.substring(0, start)
+ " "
+ value.substring(end));
.
.
But it appends only one space to the textarea when I press Tab. How can I fix it?
回答1:
It does add four spaces. You just forgot to adjust one thing:
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
You probably see the caret move by only one space. You need to change the above lines to:
// Put caret at right position again (add four for four spaces)
this.selectionStart = this.selectionEnd = start + 4;
来源:https://stackoverflow.com/questions/51236878/why-does-this-textarea-appear-to-only-add-one-space-instead-of-four