将空格添加到文本区域



我正试图在文本区域中添加4个空格。

但是,它只增加了1个空格。

$(document).delegate('#test', '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;
        $(this).val($(this).val().substring(0, start)
            + " " + " " + " " + " "
            + $(this).val().substring(end));
            $(this).get(0).selectionStart =
            $(this).get(0).selectionEnd = start + 1;
    }
});

编辑:

我已经测试了 ,它按原样输出"  "并向tetpare输出:" "。

如何强制添加4个空格?

$("textarea").on('keydown', function(e) {
    if(e.keyCode == 9) {
      e.preventDefault();
      for(var i=0; i<4; i++) {
        	var start = this.selectionStart,
          end = this.selectionEnd,
          value = $(this).val();
        	$(this).val(value.substring(0, start)
                    + " "
                    + value.substring(end));
        	this.selectionStart = this.selectionEnd = start + 1;
      }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="30" rows="10"></textarea>

$(document).delegate('#test', '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;
    $(this).val($(this).val().substring(0, start)
        + &nbsp;&nbsp;&nbsp;&nbsp;
        + $(this).val().substring(end));
        $(this).get(0).selectionStart =
        $(this).get(0).selectionEnd = start + 1;
}

});

一种解决方案是调用一个函数四次。

$(document).delegate('#code', 'keydown', function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) {
        e.preventDefault();
        add_space();
        add_space();
        add_space();
        add_space();
    }
});
function add_space()
{
    $code = $("#code");
            var start = $code.get(0).selectionStart;
        var end = $code.get(0).selectionEnd;
        $code.val($code.val().substring(0, start)
            + " "
            + $code.val().substring(end));
            $code.get(0).selectionStart =
            $code.get(0).selectionEnd = start + 1;
}

只使用不可破坏的空间:&nbsp;而不是常规空间。

最新更新