如何禁用 Tab 键切换输入框,并作为字符输入


比如就是 SF 的正文 textarea,如何实现在插入代码的时候按下 tab 键 只在代码块里缩进,而光标不会选中发布问题的提交按钮?

前端 textinput JavaScript

Dazed 10 years, 2 months ago

keydown事件,判断键值是否是9,如果是,则实现缩进,可以使用4个空格或者水平制表符:\t

lolicn answered 10 years, 2 months ago

给输入框添加 keydown 事件,进行判断,如果按下的是 tab 键,则阻止默认的行为。

hellsa answered 10 years, 2 months ago

測試通過,行爲於 SF 編輯器幾乎一致( "\t" 改成 " " 就完全一致了)。

順便吐槽 SF 編輯器選中多行文本沒有像 Sublime Text 那樣自動每行縮進一格。


 var el = document.querySelector('textarea');

el.addEventListener("keydown", function(e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === 9) {
        var start = el.selectionStart,
            end = el.selectionEnd;

        el.value = el.value.substring(0, start)
                + "\t"
                + el.value.substring(end);

        el.selectionStart = el.selectionEnd = start + 1;

        e.preventDefault();
    }
})

參見: http://stackoverflow.com/questions/6140632/how-to-handle-tab-in-textarea

想要 Sublime Text 一樣選中多行文本按 Tab 時每行縮進一 Tab 的話可以用這段:


 var el = document.querySelector('textarea');

el.addEventListener("keydown", function(e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === 9) {
        var start = el.selectionStart,
            end = el.selectionEnd, 
            value = el.value;

        var lineStart = value.lastIndexOf('\n', start),
            lineEnd = value.indexOf('\n', end),
            offset = 0;

        if (lineStart === -1) lineStart = 0;
        if (lineEnd === -1) lineEnd = value.length;

        if (lineStart === lineEnd);
        else if (lineStart !== 0) lineStart += 1;

        lines = value.substring(lineStart, lineEnd).split('\n');
        console.log([lineStart, lineEnd], lines);

        if (lines.length > 1) {
            offset = lines.length;
            lines = '\t' + lines.join('\n\t');

            el.value = value.substring(0, lineStart) + lines + value.substring(lineEnd);

            el.selectionStart = start + 1;
            el.selectionEnd = end + offset;
        } else {
            offset = 1;
            lines = lines[0];

            el.value = value.substring(0, start) + '\t' + value.substring(end);

            el.selectionStart = el.selectionEnd = start + offset;
        }

        e.preventDefault();
    }
})

Eidolem answered 10 years, 2 months ago

Your Answer