Why does this textarea appear to only add one space instead of four?

假装没事ソ 提交于 2019-12-11 11:53:02

问题


Here is my code:

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

It handles Tab key in the <textarea>. It appends \t to the textarea when you press the Tab key. Now I want to add 4 spaces instead. Here is my new version:

.
.
 $this.val(value.substring(0, start)
             + "    "
             + value.substring(end));
.
.

But it appends only one space to the textarea when I press Tab. How can I fix it?


回答1:


It does add four spaces. You just forgot to adjust one thing:

// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;

You probably see the caret move by only one space. You need to change the above lines to:

// Put caret at right position again (add four for four spaces)
this.selectionStart = this.selectionEnd = start + 4;


来源:https://stackoverflow.com/questions/51236878/why-does-this-textarea-appear-to-only-add-one-space-instead-of-four

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