为什么这个文本区域似乎只添加一个空格而不是四个空格? [英] Why does this textarea appear to only add one space instead of four?

查看:95
本文介绍了为什么这个文本区域似乎只添加一个空格而不是四个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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个空格.这是我的新版本:

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));
.
.

但是当我按 Tab 时,它仅将一个空间附加到文本区域.我该如何解决?

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

推荐答案

确实添加四个空格.您只是忘了调整一件事:

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;

这篇关于为什么这个文本区域似乎只添加一个空格而不是四个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆