【发布时间】:2014-12-29 15:08:01
【问题描述】:
我试图在按下 Tab 键时插入四个空格。我正在使用以下代码(请参阅spaces = "\t"),但是当我将其切换到spaces = " " 时,按下制表符时只插入一个空格。我也试过""+""+""+"":
$(function () {
$('textarea').keydown(function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var start = $(this).get(0).selectionStart;
var end = $(this).get(0).selectionEnd;
// set textarea value to: text before caret + tab + text after caret
spaces = "\t"
$(this).val($(this).val().substring(0, start)
+ spaces
+ $(this).val().substring(end));
// put caret at right position again
$(this).get(0).selectionStart =
$(this).get(0).selectionEnd = start + 1;
}
});
});
注意:这是在基于浏览器的 textarea/ide 中插入空格。
【问题讨论】:
-
在 Chrome/IE9/FF32 中为我工作 - jsfiddle.net/17auq970 - 你使用的是哪个浏览器?
-
不完全相关,但不需要
e.which检查,jQuery 会为您标准化属性(which)。 -
谢谢@Teemu 好主意
-
您可以尝试将
font-family专门设置为monospace。否则这工作得很好。
标签: javascript jquery html keycode