这是我的代码:
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();
}
});
它处理
<textarea>
中的Tab键。当您按Tab键时,它会将\t
附加到文本区域。现在,我想添加4个空格。这是我的新版本:.
.
$this.val(value.substring(0, start)
+ " "
+ value.substring(end));
.
.
但是当我按Tab时,它仅将一个空格附加到文本区域。我该如何解决?
最佳答案
它确实添加了四个空格。您只是忘了调整一件事:
// 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;
关于javascript - 为什么这个文本区域似乎只添加一个空格而不是四个空格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51236878/