为什么这个 textarea 似乎只添加一个 space 而不是四个?
Why does this textarea appear to only add one space instead of four?
这是我的代码:
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 spaces。这是我的新版本:
.
.
$this.val(value.substring(0, start)
+ " "
+ value.substring(end));
.
.
但是当我按下 Tab 时,它只会将 one space 添加到文本区域。我该如何解决?
它确实添加了四个space。你只是忘了调整一件事:
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
您可能看到插入符号只移动了一个 space。您需要将以上几行更改为:
// Put caret at right position again (add four for four spaces)
this.selectionStart = this.selectionEnd = start + 4;
这是我的代码:
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 spaces。这是我的新版本:
.
.
$this.val(value.substring(0, start)
+ " "
+ value.substring(end));
.
.
但是当我按下 Tab 时,它只会将 one space 添加到文本区域。我该如何解决?
它确实添加了四个space。你只是忘了调整一件事:
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
您可能看到插入符号只移动了一个 space。您需要将以上几行更改为:
// Put caret at right position again (add four for four spaces)
this.selectionStart = this.selectionEnd = start + 4;