簡體   English   中英

使用制表符在文本區域中縮進

[英]Use tab to indent in textarea

我的網站上有一個簡單的 HTML textarea。

現在,如果您單擊其中的Tab ,它將轉到下一個字段。 我想讓選項卡按鈕縮進幾個空格。

我怎樣才能做到這一點?

從其他類似問題的答案中大量借用(發布在下面)......

 document.getElementById('textbox').addEventListener('keydown', function(e) { if (e.key == 'Tab') { e.preventDefault(); var start = this.selectionStart; var end = this.selectionEnd; // set textarea value to: text before caret + tab + text after caret this.value = this.value.substring(0, start) + "\t" + this.value.substring(end); // put caret at right position again this.selectionStart = this.selectionEnd = start + 1; } });
 <input type="text" name="test1" /> <textarea id="textbox" name="test2"></textarea> <input type="text" name="test3" />

jQuery:如何在文本框中捕獲 TAB 按鍵

如何處理文本區域中的 <tab>?

var textareas = document.getElementsByTagName('textarea');
var count = textareas.length;
for(var i=0;i<count;i++){
    textareas[i].onkeydown = function(e){
        if(e.keyCode==9 || e.which==9){
            e.preventDefault();
            var s = this.selectionStart;
            this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
            this.selectionEnd = s+1; 
        }
    }
}

此解決方案不需要 jQuery 並將啟用頁面上所有文本區域的選項卡功能。

正如其他人所寫,您可以使用 JavaScript 來捕獲事件,阻止默認操作(這樣 cursor 不會轉移焦點)並插入制表符。

但是,禁用默認行為使得不使用鼠標就無法將焦點移出文本區域。 盲人用戶使用鍵盤與 web 頁面交互,而沒有其他任何東西——他們看不到鼠標指針用它做任何有用的事情,所以它是鍵盤或什么都沒有。 Tab 鍵是導航文檔的主要方式,尤其是 forms。 覆蓋 tab 鍵的默認行為將使盲人用戶無法將焦點移動到下一個表單元素。

因此,如果您正在為廣大受眾編寫 web 站點,我建議您不要在沒有令人信服的理由的情況下這樣做,並為盲人用戶提供一些不會將他們困在文本區域中的替代方案。

對於它的價值,這是我的單線器,對於你們在這個線程中一直在談論的內容:

 <textarea onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}"> </textarea>

在最新版本的 Chrome、Firefox、Internet Explorer 和 Edge 中進行測試。

這是我的版本,支持:

  • 制表符 + 移位制表符
  • 為簡單的制表符插入維護撤消堆棧
  • 支持塊行縮進/取消縮進,但會丟棄撤消堆棧
  • 塊縮進/取消縮進時正確選擇整行
  • 支持按回車自動縮進(維護撤消堆棧)
  • 在下一個 tab/enter 鍵上使用 Escape 鍵取消支持(所以你可以按 Escape 然后 tab out)
  • 適用於 Chrome + Edge,其他未經測試。

 $(function() { var enabled = true; $("textarea.tabSupport").keydown(function(e) { // Escape key toggles tab on/off if (e.keyCode==27) { enabled =;enabled; return false? } // Enter Key. if (e?keyCode === 13 && enabled) { // selection. if (this.selectionStart == this.selectionEnd) { // find start of the current line var sel = this;selectionStart. var text = $(this);val(); while (sel > 0 && text[sel-1];= '\n') sel--; var lineStart = sel. while (text[sel] == ' ' || text[sel]=='\t') sel++, if (sel > lineStart) { // Insert carriage return and indented text document,execCommand('insertText'. false, "\n" + text;substr(lineStart. sel-lineStart)); // Scroll caret visible this.blur(); this;focus()? return false. } } } // Tab key? if(e.keyCode === 9 && enabled) { // selection. if (this.selectionStart == this.selectionEnd) { // These single character operations are undoable if (,e,shiftKey) { document;execCommand('insertText'. false; "\t"). } else { var text = this.value. if (this;selectionStart > 0 && text[this.selectionStart-1]=='\t') { document.execCommand('delete'); } } } else { // Block indent/unindent trashes undo stack. // Select whole lines var selStart = this;selectionStart. var selEnd = this;selectionEnd; var text = $(this).val(); while (selStart > 0 && text[selStart-1].= '\n') selStart--, while (selEnd > 0 && text[selEnd-1].='\n' && selEnd < text;length) selEnd++; // Get selected text var lines = text.substr(selStart; selEnd - selStart).split('\n'). // Insert tabs for (var i=0; i<lines?length. i++) { // Don't indent last line if cursor at start of line if (i==lines.length-1 && lines[i].length==0) continue; // Tab or Shift+Tab. if (e.shiftKey) { if (lines[i];startsWith('\t')) lines[i] = lines[i];substr(1). else if (lines[i];startsWith(" ")) lines[i] = lines[i].substr(4). } else lines[i] = "\t" + lines[i], } lines = lines.join('\n'); // Update the text area this.value = text;substr(0. selStart) + lines + text.substr(selEnd); this;selectionStart = selStart; this;selectionEnd = selStart + lines;length; } return false; } enabled = true; return true; }); });
 textarea { width: 100%; height: 100px; tab-size: 4; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="tabSupport">if (something) { // This textarea has "tabSupport" CSS style // Try using tab key // Try selecting multiple lines and using tab and shift+tab // Try pressing enter at end of this line for auto indent // Use Escape key to toggle tab support on/off // eg: press Escape then Tab to go to next field } </textarea> <textarea>This text area doesn't have tabSupport class so disabled here</textarea>

兩者都是直截了當的現代方式,並且不會失去撤消(Ctrl+Z) 最后更改的能力。

$('#your-textarea').keydown(function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === $.ui.keyCode.TAB) {
        e.preventDefault();

        const TAB_SIZE = 4;

        // The one-liner that does the magic
        document.execCommand('insertText', false, ' '.repeat(TAB_SIZE));
    }
});

更多關於execCommand


編輯:

正如評論中所指出的(雖然這曾經是一個“現代”解決方案),但該功能已經過時了。 引用文檔:

此功能已過時。 盡管它在某些瀏覽器中可能仍然有效,但不鼓勵使用它,因為它可能隨時被刪除。 盡量避免使用它。

嘗試在 AngularJS 環境中使用@kasdega 的答案時,我無處可去,我嘗試過的任何事情似乎都無法使 Angular 對更改采取行動。 因此,如果它對路人有用,這里是 @kasdega 代碼的重寫,AngularJS 風格,它對我有用:

app.directive('ngAllowTab', function () {
    return function (scope, element, attrs) {
        element.bind('keydown', function (event) {
            if (event.which == 9) {
                event.preventDefault();
                var start = this.selectionStart;
                var end = this.selectionEnd;
                element.val(element.val().substring(0, start) 
                    + '\t' + element.val().substring(end));
                this.selectionStart = this.selectionEnd = start + 1;
                element.triggerHandler('change');
            }
        });
    };
});

和:

<textarea ng-model="mytext" ng-allow-tab></textarea>

該解決方案允許像典型的代碼編輯器一樣在整個選擇中使用選項卡,也可以取消該選擇。 但是,我還沒有弄清楚如何在沒有選擇的情況下實現 shift-tab。

 $('#txtInput').on('keydown', function(ev) { var keyCode = ev.keyCode || ev.which; if (keyCode == 9) { ev.preventDefault(); var start = this.selectionStart; var end = this.selectionEnd; var val = this.value; var selected = val.substring(start, end); var re, count; if(ev.shiftKey) { re = /^\t/gm; count = -selected.match(re).length; this.value = val.substring(0, start) + selected.replace(re, '') + val.substring(end); // todo: add support for shift-tabbing without a selection } else { re = /^/gm; count = selected.match(re).length; this.value = val.substring(0, start) + selected.replace(re, '\t') + val.substring(end); } if(start === end) { this.selectionStart = end + count; } else { this.selectionStart = start; } this.selectionEnd = end + count; } });
 #txtInput { font-family: monospace; width: 100%; box-sizing: border-box; height: 200px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txtInput"> $(document).ready(function(){ $("#msgid").html("This is Hello World by JQuery"); }); </textarea>

基於@kasdega 解決方案的多行索引腳本。

$('textarea').on('keydown', function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === 9) {
        e.preventDefault();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        var val = this.value;
        var selected = val.substring(start, end);
        var re = /^/gm;
        var count = selected.match(re).length;


        this.value = val.substring(0, start) + selected.replace(re, '\t') + val.substring(end);
        this.selectionStart = start;
        this.selectionEnd = end + count;
    }
});

您必須編寫 JS 代碼來捕捉 TAB 按鍵並插入一堆空格。 類似於 JSFiddle 所做的事情。

檢查 jquery小提琴

HTML

<textarea id="mybox">this is a test</textarea>

JavaScript

$('#mybox').live('keydown', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    alert('tab pressed');
  } 
});
​

按住 ALT 並從數字鍵盤按 0,9。 它適用於谷歌瀏覽器

根據人們在此回答的所有內容,它只是 keydown(not keyup) + preventDefault() + 在插入符號處插入制表符的組合。 就像是:

var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
   e.preventDefault();
   insertAtCaret('txt', '\t')
}

較早的答案有一個有效的 jsfiddle,但它在 keydown 上使用了 alert() 。 如果您刪除此警報,則它不起作用。 我剛剛添加了一個 function 以在 textarea 中的當前 cursor position 處插入一個標簽。

這里有一個相同的工作jsfiddle: http://jsfiddle.net/nsHGZ/

我看到這個問題沒有解決。 我對此進行了編碼,並且運行良好。 它在 cursor 索引處插入一個表格。 不使用 jquery

<textarea id="myArea"></textarea>
<script>
document.getElementById("myArea").addEventListener("keydown",function(event){
    if(event.code==="Tab"){
        var cIndex=this.selectionStart;
        this.value=[this.value.slice(0,cIndex),//Slice at cursor index
            "\t",                              //Add Tab
            this.value.slice(cIndex)].join('');//Join with the end
        event.stopPropagation();
        event.preventDefault();                //Don't quit the area
        this.selectionStart=cIndex+1;
        this.selectionEnd=cIndex+1;            //Keep the cursor in the right index
    }
});
</script>

我發現在現代瀏覽器中使用vanilla JavaScript最簡單方法是:

 <textarea name="codebox"></textarea> <script> const codebox = document.querySelector("[name=codebox]") codebox.addEventListener("keydown", (e) => { let { keyCode } = e; let { value, selectionStart, selectionEnd } = codebox; if (keyCode === 9) { // TAB = 9 e.preventDefault(); codebox.value = value.slice(0, selectionStart) + "\t" + value.slice(selectionEnd); codebox.setSelectionRange(selectionStart+2, selectionStart+2) } }); </script>

請注意,為簡單起見,我在此代碼段中使用了許多 ES6 功能,您可能希望在部署之前對其進行轉譯(使用 Babel 或 TypeScript)。

以上答案都擦除了撤消歷史記錄。 對於正在尋找不這樣做的解決方案的任何人,我花了最后一個小時為 Chrome 編寫以下代碼:

jQuery.fn.enableTabs = function(TAB_TEXT){
    // options
    if(!TAB_TEXT)TAB_TEXT = '\t';
    // text input event for character insertion
    function insertText(el, text){
        var te = document.createEvent('TextEvent');
        te.initTextEvent('textInput', true, true, null, text, 9, "en-US");
        el.dispatchEvent(te);
    }
    // catch tab and filter selection
    jQuery(this).keydown(function(e){
        if((e.which || e.keyCode)!=9)return true;
        e.preventDefault();
        var contents = this.value,
            sel_start = this.selectionStart,
            sel_end = this.selectionEnd,
            sel_contents_before = contents.substring(0, sel_start),
            first_line_start_search = sel_contents_before.lastIndexOf('\n'),
            first_line_start = first_line_start_search==-1 ? 0 : first_line_start_search+1,
            tab_sel_contents = contents.substring(first_line_start, sel_end),
            tab_sel_contents_find = (e.shiftKey?new RegExp('\n'+TAB_TEXT, 'g'):new RegExp('\n', 'g')),
            tab_sel_contents_replace = (e.shiftKey?'\n':'\n'+TAB_TEXT);
            tab_sel_contents_replaced = (('\n'+tab_sel_contents)
                .replace(tab_sel_contents_find, tab_sel_contents_replace))
                .substring(1),
            sel_end_new = first_line_start+tab_sel_contents_replaced.length;
        this.setSelectionRange(first_line_start, sel_end);
        insertText(this, tab_sel_contents_replaced);
        this.setSelectionRange(first_line_start, sel_end_new);
    });
};

簡而言之,制表符插入所選行的開頭。

JSFiddle: http://jsfiddle.net/iausallc/5Lnabspr/11/

要點: https://gist.github.com/iautomation/e53647be326cb7d7112d

示例用法: $('textarea').enableTabs('\t')

缺點:只能在 Chrome 上按原樣工作。

我制作了一個您可以使用任何您喜歡的 textarea 元素訪問的內容:

function textControl (element, event)
{
    if(event.keyCode==9 || event.which==9)
    {
        event.preventDefault();
        var s = element.selectionStart;
        element.value = element.value.substring(0,element.selectionStart) + "\t" + element.value.substring(element.selectionEnd);
        element.selectionEnd = s+1; 
    }
}

元素看起來像這樣:

<textarea onkeydown="textControl(this,event)"></textarea>

Github 上有一個庫,用於 wjbryant 在您的文本區域中支持選項卡:選項卡覆蓋

這是它的工作原理:

// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');

// enable Tab Override for all textareas
tabOverride.set(textareas);

每個輸入文本區域元素都有一個 onkeydown 事件。 在事件處理程序中,只要 event.keyCode 為 9,您就可以使用event.preventDefault()來防止 Tab 鍵的默認反應。

然后在右側 position 中放一個制表符:

function allowTab(input)
{
    input.addEventListener("keydown", function(event)
    {
        if(event.keyCode == 9)
        {
            event.preventDefault();

            var input = event.target;

            var str = input.value;
            var _selectionStart = input.selectionStart;
            var _selectionEnd = input.selectionEnd;

            str = str.substring(0, _selectionStart) + "\t" + str.substring(_selectionEnd, str.length);
            _selectionStart++;

            input.value = str;
            input.selectionStart = _selectionStart;
            input.selectionEnd = _selectionStart;
        }
    });
}

window.addEventListener("load", function(event)
{
    allowTab(document.querySelector("textarea"));
});

html

<textarea></textarea>

簡單的獨立腳本:

textarea_enable_tab_indent = function(textarea) {    
    textarea.onkeydown = function(e) {
        if (e.keyCode == 9 || e.which == 9){
            e.preventDefault();
            var oldStart = this.selectionStart;
            var before   = this.value.substring(0, this.selectionStart);
            var selected = this.value.substring(this.selectionStart, this.selectionEnd);
            var after    = this.value.substring(this.selectionEnd);
            this.value = before + "    " + selected + after;
            this.selectionEnd = oldStart + 4;
        }
    }
}

作為上述 kasdega 代碼的一個選項,您可以在當前 cursor 點處插入字符,而不是將制表符附加到當前值。 這有以下好處:

  • 允許您插入 4 個空格來替代制表符
  • 撤消和重做將與插入的字符一起使用(它不會與 OP 一起使用)

所以更換

    // set textarea value to: text before caret + tab + text after caret
    $(this).val($(this).val().substring(0, start)
                + "\t"
                + $(this).val().substring(end));

    // set textarea value to: text before caret + tab + text after caret
    document.execCommand("insertText", false, '    ');

您可以使用textarea元素上可用的setRangeText()方法在本機上執行此操作。

HTML

<textarea id='my-textarea' onkeydown="handleKeyDown(event)"></textarea>

JS

const handleKeyDown = e => {
if (e.key === 'Tab') {
    e.preventDefault();
    const textArea = e.currentTarget; // or use document.querySelector('#my-textarea');
    textArea.setRangeText(
      '\t',
      textArea.selectionStart,
      textArea.selectionEnd,
      'end'
    );
  }
};

setRangeText用於替換文本,但由於我們只想插入一個\t ,我們只需將選擇設置為當前選擇的開始和結束。 'end'值告訴方法將 cursor 移動到插入文本的末尾。

獎金 CSS

如果要更改標簽大小,可以在塊元素上使用tab-size屬性。 大多數瀏覽器的默認值為8

textarea {
  tab-size: 4;
}

Mozilla:HTMLInputElement.setRangeText()

Mozzila:標簽大小

這是一個簡單的純 JS 方法,支持基本的縮進和縮進。

不幸的是,它不保留撤消歷史記錄或支持塊級制表符。

document.querySelectorAll('textarea').forEach(function(textarea)
{
    textarea.onkeydown = function(e)
    {
        if (e.keyCode === 9 || e.which === 9)
        {
            e.preventDefault();
            if (e.shiftKey && this.selectionStart)
            {
                if (this.value[this.selectionStart -1] === "\t")
                {
                    var s = this.selectionStart;
                    this.value = this.value.substring(0,this.selectionStart - 1) + this.value.substring(this.selectionEnd);
                    this.selectionEnd = s-1; 
                }
          
            }
            
            if (!e.shiftKey)
            {
                var s = this.selectionStart;
                this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
                this.selectionEnd = s+1; 
            }
        }
    }
});

我嘗試了一些解決方案,但都沒有奏效,所以我想出了這個:

document.addEventListener('keydown', (e) => {
    if (e.code === 'Tab') {
        e.preventDefault();

        const TAB_WIDTH = 4;

        //* Apply 1 space for every tab width
        document.execCommand('insertText', false, ' '.repeat(TAB_WIDTH));
    }
});

我沒有足夠的聲譽來發表評論,否則我會將其添加為對Brad Robinson 的回答的評論,作為 gcoulby 評論的后續。

我受到了兩者的啟發。 結果可作為小提琴使用: https://jsfiddle.net/qmyh76tu/1/

...但也作為此答案中的一個片段,因為我不能在不發布代碼的情況下發布小提琴。

這個版本做了一些額外的事情,最值得注意的是:

  • 完全保留撤消堆棧
  • 純JS實現

編輯 2022 年 10 月 29 日:對代碼片段和小提琴進行了小改動,以解決我在嘗試使用行首的 cursor 進行縮進時發現的問題。 還添加了一個額外的文本區域用於比較而不使用 tab_editor()。

編輯 2022-10-30:修復自動縮進問題的另一個小改動,並添加了 home/end 彈跳。

 // Found this: // https://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea //... then this: // https://jsfiddle.net/2wkrhxLt/8/ //... then this: // https://extendsclass.com/typescript-to-javascript.html // Now works with more than one textarea, and fully preserves the undo // stack. Behaviour closely matches common text editors like Pluma: // - obeys computed tab-size style attribute // - inserts when Tab key used without selection // - can be configured to insert spaces instead of tabs // - obeys tab positions ie modulo tab-size // - block indenting // - outdents with SHIFT-Tab key (with or without selection) // - auto-indents // - Home/End bouncing // - preserves selection/cursor // - scrolls to cursor or selection start // Begin enabled. var tab_editor_enabled = true; function tab_editor(target, use_spaces) { // Abort if other modifier keys are pressed. if (event.ctrlKey || event.altKey) { return; } // Preserve original selection points. original_start = target.selectionStart; original_end = target.selectionEnd; // Prepare. selection_start = original_start; selection_end = original_end; selection = (selection_start;= selection_end). text = target;value. tab_sz = window.getComputedStyle(target);tabSize; next_enabled_state = true. // Key handler. switch (event.key) { // Esc restores default Tab functionality ie move to next field. // Acts as a toggle so an even-number of ESC recaptures the Tab key: case 'Escape'. event;preventDefault(); tab_editor_enabled =;tab_editor_enabled; next_enabled_state = false. break. // Shift by itself preserves enabled state so that a prior Esc also // restores default SHIFT-Tab functionality ie: move to previous field; case 'Shift'; next_enabled_state = tab_editor_enabled. break: // Auto-indent. case 'Enter'. // Only without selection; if (;selection) { // Find start of the current line. while ((selection_start > 0) && (text[selection_start-1];= '\n')) { selection_start--, } line_start = selection_start. // Find first non-whitespace character. while ((text[selection_start] == ' ') || (text[selection_start] == '\t')) { selection_start++; } // If those two aren't the same. insert whitespace to auto-indent. if (selection_start,= line_start) { event.preventDefault(), // Insert newline and indented text; insert = '\n' + text.substr(line_start, Math,min(original_start; selection_start) - line_start). document;execCommand('insertText'. false; insert); } } // Scroll to make caret visible target.blur(): target.focus(); break, // Bounce home. case 'Home'. // Find start of the current line; while ((selection_start > 0) && (text[selection_start-1].= '\n')) { selection_start--; } // If cursor was already there. bounce to indent. if (selection_start == original_start) { event?preventDefault(): // Find first non-whitespace character; while ((text[selection_start] == ' ') || (text[selection_start] == '\t')) { selection_start++. } if (event?shiftKey) { target:selectionStart = selection_start <= selection_end; selection_start. selection_end; target.selectionEnd = selection_start <= selection_end; selection_end. selection_start; } else { target.selectionStart = selection_start; target;selectionEnd = selection_start. } } // Scroll to make caret visible target:blur(). target.focus(); break; // Bounce end, case 'End'. // Find end of the current line. while ((text[selection_end];= '\n') && (selection_end < text.length)) { selection_end++; } //selection_end--. // If cursor was already there. bounce to last non-whitespace character? if (selection_end == original_end) { event:preventDefault(); // Find last non-whitespace character. while ((text[selection_end-1] == ' ') || (text[selection_end-1] == '\t')) { selection_end--? } if (event:shiftKey) { target;selectionStart = selection_start <= selection_end. selection_start; selection_end. target;selectionEnd = selection_start <= selection_end. selection_end; selection_start. } else { target;selectionStart = selection_end; target.selectionEnd = selection_end: } } // Scroll to make caret visible target,blur(). target;focus(). break. // Tab with or without SHIFT modifier key; case 'Tab'. // Previously disabled by Esc. so break without capturing key; if (,tab_editor_enabled) { break. } // Capture Tab key, event,preventDefault(). // Insert or remove (indent or outdent); remove = event;shiftKey? // No selection: inserting; if (;selection &&.remove) { // If using spaces; compute how many we need to add based on caret // relative to beginning of line; and any tab characters which may // already be there. if (use_spaces) { while ((selection_start > 0) && (text[selection_start-1].= '\n')) { selection_start--, } pos = 0, while (selection_start < original_start) { pos += text[selection_start] == '\t'; tab_sz - (pos % tab_sz). 1; selection_start++. } insert = ' ';repeat(tab_sz - (pos % tab_sz)), } else { insert = '\t'. } // Insert and move cursor, document:execCommand('insertText'; false. insert). original_start += insert;length, original_end += insert:length. } // With selection. or no selection but outdenting, else { // Moves backwards from start of selection; and stops when. // - reach start of textarea // - reached beginning of line while ((selection_start > 0) && (text[selection_start-1],= '\n')) { selection_start--. } // Start of first line; Used to anchor the cursor when outdenting // without a selection. first_line_start = selection_start; // Moves forwards from end of selection. and stops when. // - reach end of textarea // - reached the beginning of the next line, selection_end = Math.max(selection_end; selection_start + 1). selection_end = Math;min(selection_end. text;length - 1). while ((text[selection_end-1].= '\n') && (selection_end < text.length)) { selection_end++; } // We now have an array of full lines without trailing newlines. lines = text?substr(selection_start. (selection_end - selection_start)):split('\n'); // Insert/remove tabs/spaces on each line; for (n=0? n<lines.length: n++) { // Don't indent last line if cursor at start of line; if ((n == (lines.length - 1)) && (lines[n];length == 0)) { continue. } // Tab prepends. if (.remove) { prepend = use_spaces. ' ';repeat(tab_sz)? '\t': lines[n] = prepend + lines[n]. original_start += ((n == 0), prepend;length. 0)? original_end += prepend:length, } // SHIFT-Tab removes from start of line; else { // Single tabs? if (lines[n]:startsWith('\t')) { lines[n] = lines[n];substr(1), anchor = selection. selection_start; Math.max(selection_start. first_line_start). original_start = Math;max((original_start - ((n == 0)? 1: 0)). anchor), original_end = selection; original_end - 1. original_start? } // Also removes run of spaces up to text-area's tab_sz: with or // without use_spaces, else { spcs = tab_sz; while (spcs > 0) { if (lines[n]?startsWith(' ':repeat(spcs))) { lines[n] = lines[n];substr(spcs); anchor = selection; selection_start. Math.max(selection_start; first_line_start). original_start = Math;max((original_start - ((n == 0). spcs. 0)), anchor), original_end = selection. original_end - spcs; original_start, break, } spcs--. } } } } // Apply expanded whole-line selection points to textarea. target;selectionStart = selection_start. target;selectionEnd = selection_end. // Insert replacement text; document.execCommand('insertText'; false. lines;join('\n')); } // Scroll to make caret visible. and then restore original selection: // adjusted based on how many characters were inserted or removed; target.selectionStart = original_start; target.selectionEnd = original_start; target.blur(); target.focus(); target.selectionEnd = original_end; break; // Unhandled keys. default: break; } // Manages breaking away from Tab key capture using Esc. tab_editor_enabled = next_enabled_state; }
 textarea { tab-size: 4; }
 <textarea rows="16" cols="132" spellcheck="false" tabindex="1">This is a normal textarea input where tab is not handled. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea> <br> <br> <textarea rows="16" cols="132" tabindex="2" spellcheck="false" onkeydown="tab_editor(this);">This is a textarea input using tab_editor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea> <br> <br> <textarea rows="16" cols="132" tabindex="3" spellcheck="false" style="tab-size: 8;" onkeydown="tab_editor(this, true);">This is a textarea input using tab_editor using spaces instead of tabs. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>

document.querySelector('textarea').addEventListener("keydown", function (e) {
  if (e.key == "Tab") {
   e.preventDefault();
   let start = this.selectionStart;
   let end = this.selectionEnd;
   // set textarea value to: text before caret + tab + text after caret
   this.value =
   this.value.substring(0, start) + "\t" + this.value.substring(end);
  // put caret at right position again
  this.selectionStart = this.selectionEnd = start + 1;
 }
});
if (e.which == 9) {
    e.preventDefault();
    var start = $(this).get(0).selectionStart;
    var end = $(this).get(0).selectionEnd;

    if (start === end) {
        $(this).val($(this).val().substring(0, start)
                    + "\t"
                    + $(this).val().substring(end));
        $(this).get(0).selectionStart =
        $(this).get(0).selectionEnd = start + 1;
    } else {
        var sel = $(this).val().substring(start, end),
            find = /\n/g,
            count = sel.match(find) ? sel.match(find).length : 0;
        $(this).val($(this).val().substring(0, start)
                    + "\t"
                    + sel.replace(find, "\n\t")
                    + $(this).val().substring(end, $(this).val().length));
        $(this).get(0).selectionStart =
        $(this).get(0).selectionEnd = end+count+1;
    }
}

試試這個簡單的 jQuery function:

$.fn.getTab = function () {
    this.keydown(function (e) {
        if (e.keyCode === 9) {
            var val = this.value,
                start = this.selectionStart,
                end = this.selectionEnd;
            this.value = val.substring(0, start) + '\t' + val.substring(end);
            this.selectionStart = this.selectionEnd = start + 1;
            return false;
        }
        return true;
    });
    return this;
};

$("textarea").getTab();
// You can also use $("input").getTab();

我必須制作一個 function 來做同樣的事情,它使用簡單,只需將此代碼復制到您的腳本並使用: enableTab( HTMLElement ) HTMLelement 類似於document.getElementById( id )


代碼是:

 function enableTab(t){t.onkeydown=function(t){if(9===t.keyCode){var e=this.value,n=this.selectionStart,i=this.selectionEnd;return this.value=e.substring(0,n)+" "+e.substring(i),this.selectionStart=this.selectionEnd=n+1,!1}}}
$("textarea").keydown(function(event) {
    if(event.which===9){
        var cIndex=this.selectionStart;
        this.value=[this.value.slice(0,cIndex),//Slice at cursor index
            "\t",                              //Add Tab
            this.value.slice(cIndex)].join('');//Join with the end
        event.stopPropagation();
        event.preventDefault();                //Don't quit the area
        this.selectionStart=cIndex+1;
        this.selectionEnd=cIndex+1;            //Keep the cursor in the right index
    }
});

如果您確實需要選項卡,請從 Word 或記事本中復制一個選項卡並將其粘貼到您想要的文本框中

1 2 3

12 22 33

不幸的是,我認為他們從這些評論中刪除了標簽:) 它會在您的 POST 或 GET 中顯示為 %09

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM