Insert four spaces instead of tab

落爺英雄遲暮 提交于 2019-12-10 14:49:27

问题


I am trying to insert four spaces when the tab key is pressed. I was using the following code (see spaces = "\t"), but when I switch it to spaces = " " only one space is inserted when I press tab. I also tried " " + " " + " " + " ":

$(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;
    }
  });
});

NOTE: This is to insert spaces in a browser-based textarea/ide.


回答1:


Your code works fine but you simply put caret to the wrong place. Change the last line to:

this.selectionStart = this.selectionEnd = start + spaces.length;

DEMO: http://jsfiddle.net/qdqrs3cw/




回答2:


try to insert "&nbsp&nbsp&nbsp&nbsp" instead of four spaces

PS sorry have not seen that spaces are needed in textarea, in this case HTML entities will no help



来源:https://stackoverflow.com/questions/27691291/insert-four-spaces-instead-of-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!