为什么这个textarea似乎只添加一个空格而不是四个?
这是我的代码:
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(); } });
它处理中的Tab键。 当您按Tab键时,它会将
\t
附加到textarea。 现在我想添加4个空格。 这是我的新版本:
. . $this.val(value.substring(0, start) + " " + value.substring(end)); . .
但是当我按Tab键时,它只向textarea添加一个空格。 我该如何解决?
它确实增加了四个空格。 你忘了调整一件事:
// put caret at right position again (add one for the tab) this.selectionStart = this.selectionEnd = start + 1;
您可能会看到插入符号仅移动一个空格。 您需要将以上行更改为:
// Put caret at right position again (add four for four spaces) this.selectionStart = this.selectionEnd = start + 4;