在textarea中使用tab键缩进。

时间:2022-08-23 22:36:38

I have a simple html textarea on my side. Right now if you click tab in it, it goes to the next field. I would like to make the tab button indent a few spaces instead. How can I do this? Thanks.

我这边有一个简单的html文本区。现在,如果你点击其中的tab,它就会进入下一个字段。我想让tab按钮缩进一些空格。我该怎么做呢?谢谢。

22 个解决方案

#1


97  

Borrowing heavily from other answers for similar questions (posted below)...

从其他类似问题的答案中大量借鉴(贴在下面)……

$(document).delegate('#textbox', 'keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9) {
    e.preventDefault();
    var start = this.selectionStart;
    var end = this.selectionEnd;

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

    // put caret at right position again
    this.selectionStart =
    this.selectionEnd = start + 1;
  }
});

jQuery: How to capture the TAB keypress within a Textbox

jQuery:如何在文本框中捕获选项卡按键

How to handle <tab> in textarea?

如何在textarea中处理 ?

http://jsfiddle.net/jz6J5/

http://jsfiddle.net/jz6J5/

#2


41  

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

This solution does not require jQuery and will enable tab functionality on all textareas on a page.

此解决方案不需要jQuery,并且将在页面上的所有textarea上启用选项卡功能。

#3


30  

As others have written, you can use JavaScript to capture the event, prevent the default action (so that the cursor does not shift focus) and insert a tab character.

正如其他人所写的,您可以使用JavaScript捕获事件,防止默认操作(这样游标就不会转移焦点),并插入一个制表符。

But, disabling the default behavior makes it impossible to move the focus out of the text area without using a mouse. Blind users interact with web pages using the keyboard and nothing else -- they can't see the mouse pointer to do anything useful with it, so it's keyboard or nothing. The tab key is the primary way to navigate the document, and especially forms. Overriding the default behavior of the tab key will make it impossible for blind users to move the focus to the next form element.

但是,禁用默认行为使得不使用鼠标就不可能将焦点移出文本区域。盲人用户使用键盘和网页进行交互,除此之外什么都不做——他们看不到鼠标指针,无法使用它做任何有用的事情,所以它要么是键盘,要么什么都没有。选项卡键是导航文档的主要方式,特别是表单。覆盖选项卡键的默认行为将使盲人用户无法将焦点移动到下一个表单元素。

So, if you're writing a web site for a broad audience, I'd recommend against doing this without a compelling reason, and provide some kind of alternative for blind users that doesn't trap them in the textarea.

所以,如果你要为广大的读者写一个网站,我建议你不要在没有令人信服的理由的情况下这样做,并为盲人用户提供一些不让他们陷入文本区域的替代选择。

#4


23  

For what it's worth, here's my oneliner, for what you all have been talking about in this thread:

值得注意的是,这是我的oneliner,你们在这篇文章中所讨论的:

<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>

Testest in latest editions of Chrome, Firefox, Internet Explorer and Edge.

测试最新版本的Chrome, Firefox, ie和Edge。

#5


12  

I was getting nowhere fast trying to use @kasdega's answer in an AngularJS environment, nothing I tried seemed able to make Angular act on the change. So in case it's of any use to passers by, here's a rewrite of @kasdega's code, AngularJS style, which worked for me:

在一个AngularJS环境中,我试图使用@kasdega的答案,但没有任何东西能让我在变化中做出有棱角的反应。因此,如果它对passers有任何用处,这里是对@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');
            }
        });
    };
});

and:

和:

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

#6


7  

You have to write JS code to catch TAB key press and insert a bunch of spaces. Something similar to what JSFiddle does.

您必须编写JS代码来捕获TAB键按下并插入一些空格。类似于海斯克所做的事情。

Check jquery fiddle:

检查jquery小提琴:

HTML:

HTML:

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

JavaScript:

JavaScript:

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

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

#7


7  

Multiple-line indetation script based on @kasdega solution.

基于@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;
    }
});

#8


7  

This solution allows tabbing in an entire selection like your typical code editor, and untabbing that selection too. However, I haven't figured out how to implement shift-tab when there's no selection.

这个解决方案允许像您的典型代码编辑器那样对整个选择进行制表,并取消对该选择的制表。但是,我还没有找到在没有选择时如何实现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>

#9


3  

Based on all that people had to say here on the answers, its just a combination of keydown(not keyup) + preventDefault() + insert a tab character at the caret. Something like:

基于所有人必须在这里说的答案,它只是键盘的组合(不是键)+ preventDefault() +插入一个标签字符在插入符号。喜欢的东西:

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

The earlier answer had a working jsfiddle but it used an alert() on keydown. If you remove this alert, then it didnt work. I ve just added a function to insert a tab at the current cursor position in the textarea.

前面的答案有一个可用的jsfiddle,但是它在keydown上使用了alert()。如果你删除了这个警告,它就不起作用了。我刚刚添加了一个函数来在textarea中的当前光标位置插入一个选项卡。

Here s a working jsfiddle for the same: http://jsfiddle.net/nsHGZ/

这里有一个工作的jsfiddle: http://jsfiddle.net/nsHGZ/

#10


3  

I see this subject is not solved. I coded this and it's working very well. It insert a tabulation at the cursor index. Without using jquery

我看这个问题还没有解决。我编写了这个,它运行得很好。它在游标索引处插入一个列表。不使用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>

#11


2  

Hold ALT and press 0,9 from numeric keypad. It works in google-chrome

按住ALT键,在数字键盘上按0,9。它在谷歌浏览器

#12


2  

The above answers all wipe undo history. For anyone looking for a solution that doesn't do that, I spent the last hour coding up the following for Chrome:

以上答案都抹去了历史。对于任何想要找到解决方案的人来说,我花了最后一个小时为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);
    });
};

In short, tabs are inserted at the beginning of the selected lines.

简而言之,选项卡被插入到所选行的开头。

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

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

Gist: https://gist.github.com/iautomation/e53647be326cb7d7112d

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

Example usage: $('textarea').enableTabs('\t')

示例使用:$(“文本区域”).enableTabs(‘\ t’)

Cons: Only works on Chrome as is.

缺点:只能在Chrome上运行。

#13


1  

I made one that you can access with any textarea element you like:

我做了一个,你可以访问任何你喜欢的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; 
    }
}

And the element would look like this:

元素是这样的

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

#14


0  

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

#15


0  

In addition to what @kasdega said, in Webkit in order to see the tab characters with correct indentation use the style:

除了@kasdega所说的,在Webkit中为了看到带有正确缩进的制表符使用样式:

#textbox {
    text-rendering: optimizeSpeed;
}

This is applicable to Chrome 32.

这适用于Chrome 32。

Try @kasdega's jsfiddle with this addition

试试@kasdega的jsfiddle。

#16


0  

Try this simple jQuery function:

试试这个简单的jQuery函数:

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

#17


0  

I had to make a function to do the same, It is simple to use, just copy this code to your script and use: enableTab( HTMLElement ) HTMLelement being something like document.getElementById( id )

我需要做一个函数来实现同样的功能,它很容易使用,只需将此代码复制到您的脚本并使用:enableTab(HTMLElement) HTMLElement是类似于document的东西。getElementById(id)


The code is:

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}}}

#18


0  

There is a library on Github for tab support in your textareas by wjbryant: Tab Override

Github上有一个库,用于支持wjbryant: tab覆盖

This is how it works:

这就是它的工作原理:

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

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

#19


0  

Here's my version of this, supports:

这是我的版本,支持:

  • tab + shift tab
  • 选项卡+ shift选项卡
  • maintains undo stack for simple tab character inserts
  • 维护简单的选项卡字符插入的撤销堆栈
  • supports block line indent/unindent but trashes undo stack
  • 支持块线缩进/取消缩进,但撤销堆栈
  • properly selects whole lines when block indent/unindent
  • 当块缩进/不缩进时,正确地选择整行。
  • supports auto indent on pressing enter (maintains undo stack)
  • 支持按回车键自动缩进(保持撤销栈)
  • use Escape key cancel support on next tab/enter key (so you can press Escape then tab out)
  • 在next tab/enter键上使用Escape键取消支持(因此可以按Escape键然后按tab键退出)
  • Works on Chrome + Edge, untested others.
  • 适用于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).val();
					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>

#20


0  

Every input an textarea element has a onkeydown event. In the event handler you can prevent the default reaction of the tab key by using event.preventDefault() whenever event.keyCode is 9.

每个输入一个textarea元素都有一个onkeydown事件。在事件处理程序中,可以在事件发生时使用event. preventdefault()来防止选项卡键的默认反应。键码是9。

Then put a tab sign in the right 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

html

<textarea></textarea>

#21


0  

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

#22


-2  

If you really need tabs copy a tab from word or notepad and paste it in the text box where you want it

如果你真的需要制表符,从word或记事本中复制一个制表符,粘贴到你想要的文本框中

1 2 3

1 2 3

12 22 33

12 22 33

Unfortunately I think they remove the tabs from these comments though :) It will show as %09 in your POST or GET

不幸的是,我认为他们从这些评论删除了标签:)它将显示为%09在你的文章或得到

#1


97  

Borrowing heavily from other answers for similar questions (posted below)...

从其他类似问题的答案中大量借鉴(贴在下面)……

$(document).delegate('#textbox', 'keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9) {
    e.preventDefault();
    var start = this.selectionStart;
    var end = this.selectionEnd;

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

    // put caret at right position again
    this.selectionStart =
    this.selectionEnd = start + 1;
  }
});

jQuery: How to capture the TAB keypress within a Textbox

jQuery:如何在文本框中捕获选项卡按键

How to handle <tab> in textarea?

如何在textarea中处理 ?

http://jsfiddle.net/jz6J5/

http://jsfiddle.net/jz6J5/

#2


41  

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

This solution does not require jQuery and will enable tab functionality on all textareas on a page.

此解决方案不需要jQuery,并且将在页面上的所有textarea上启用选项卡功能。

#3


30  

As others have written, you can use JavaScript to capture the event, prevent the default action (so that the cursor does not shift focus) and insert a tab character.

正如其他人所写的,您可以使用JavaScript捕获事件,防止默认操作(这样游标就不会转移焦点),并插入一个制表符。

But, disabling the default behavior makes it impossible to move the focus out of the text area without using a mouse. Blind users interact with web pages using the keyboard and nothing else -- they can't see the mouse pointer to do anything useful with it, so it's keyboard or nothing. The tab key is the primary way to navigate the document, and especially forms. Overriding the default behavior of the tab key will make it impossible for blind users to move the focus to the next form element.

但是,禁用默认行为使得不使用鼠标就不可能将焦点移出文本区域。盲人用户使用键盘和网页进行交互,除此之外什么都不做——他们看不到鼠标指针,无法使用它做任何有用的事情,所以它要么是键盘,要么什么都没有。选项卡键是导航文档的主要方式,特别是表单。覆盖选项卡键的默认行为将使盲人用户无法将焦点移动到下一个表单元素。

So, if you're writing a web site for a broad audience, I'd recommend against doing this without a compelling reason, and provide some kind of alternative for blind users that doesn't trap them in the textarea.

所以,如果你要为广大的读者写一个网站,我建议你不要在没有令人信服的理由的情况下这样做,并为盲人用户提供一些不让他们陷入文本区域的替代选择。

#4


23  

For what it's worth, here's my oneliner, for what you all have been talking about in this thread:

值得注意的是,这是我的oneliner,你们在这篇文章中所讨论的:

<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>

Testest in latest editions of Chrome, Firefox, Internet Explorer and Edge.

测试最新版本的Chrome, Firefox, ie和Edge。

#5


12  

I was getting nowhere fast trying to use @kasdega's answer in an AngularJS environment, nothing I tried seemed able to make Angular act on the change. So in case it's of any use to passers by, here's a rewrite of @kasdega's code, AngularJS style, which worked for me:

在一个AngularJS环境中,我试图使用@kasdega的答案,但没有任何东西能让我在变化中做出有棱角的反应。因此,如果它对passers有任何用处,这里是对@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');
            }
        });
    };
});

and:

和:

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

#6


7  

You have to write JS code to catch TAB key press and insert a bunch of spaces. Something similar to what JSFiddle does.

您必须编写JS代码来捕获TAB键按下并插入一些空格。类似于海斯克所做的事情。

Check jquery fiddle:

检查jquery小提琴:

HTML:

HTML:

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

JavaScript:

JavaScript:

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

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

#7


7  

Multiple-line indetation script based on @kasdega solution.

基于@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;
    }
});

#8


7  

This solution allows tabbing in an entire selection like your typical code editor, and untabbing that selection too. However, I haven't figured out how to implement shift-tab when there's no selection.

这个解决方案允许像您的典型代码编辑器那样对整个选择进行制表,并取消对该选择的制表。但是,我还没有找到在没有选择时如何实现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>

#9


3  

Based on all that people had to say here on the answers, its just a combination of keydown(not keyup) + preventDefault() + insert a tab character at the caret. Something like:

基于所有人必须在这里说的答案,它只是键盘的组合(不是键)+ preventDefault() +插入一个标签字符在插入符号。喜欢的东西:

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

The earlier answer had a working jsfiddle but it used an alert() on keydown. If you remove this alert, then it didnt work. I ve just added a function to insert a tab at the current cursor position in the textarea.

前面的答案有一个可用的jsfiddle,但是它在keydown上使用了alert()。如果你删除了这个警告,它就不起作用了。我刚刚添加了一个函数来在textarea中的当前光标位置插入一个选项卡。

Here s a working jsfiddle for the same: http://jsfiddle.net/nsHGZ/

这里有一个工作的jsfiddle: http://jsfiddle.net/nsHGZ/

#10


3  

I see this subject is not solved. I coded this and it's working very well. It insert a tabulation at the cursor index. Without using jquery

我看这个问题还没有解决。我编写了这个,它运行得很好。它在游标索引处插入一个列表。不使用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>

#11


2  

Hold ALT and press 0,9 from numeric keypad. It works in google-chrome

按住ALT键,在数字键盘上按0,9。它在谷歌浏览器

#12


2  

The above answers all wipe undo history. For anyone looking for a solution that doesn't do that, I spent the last hour coding up the following for Chrome:

以上答案都抹去了历史。对于任何想要找到解决方案的人来说,我花了最后一个小时为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);
    });
};

In short, tabs are inserted at the beginning of the selected lines.

简而言之,选项卡被插入到所选行的开头。

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

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

Gist: https://gist.github.com/iautomation/e53647be326cb7d7112d

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

Example usage: $('textarea').enableTabs('\t')

示例使用:$(“文本区域”).enableTabs(‘\ t’)

Cons: Only works on Chrome as is.

缺点:只能在Chrome上运行。

#13


1  

I made one that you can access with any textarea element you like:

我做了一个,你可以访问任何你喜欢的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; 
    }
}

And the element would look like this:

元素是这样的

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

#14


0  

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

#15


0  

In addition to what @kasdega said, in Webkit in order to see the tab characters with correct indentation use the style:

除了@kasdega所说的,在Webkit中为了看到带有正确缩进的制表符使用样式:

#textbox {
    text-rendering: optimizeSpeed;
}

This is applicable to Chrome 32.

这适用于Chrome 32。

Try @kasdega's jsfiddle with this addition

试试@kasdega的jsfiddle。

#16


0  

Try this simple jQuery function:

试试这个简单的jQuery函数:

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

#17


0  

I had to make a function to do the same, It is simple to use, just copy this code to your script and use: enableTab( HTMLElement ) HTMLelement being something like document.getElementById( id )

我需要做一个函数来实现同样的功能,它很容易使用,只需将此代码复制到您的脚本并使用:enableTab(HTMLElement) HTMLElement是类似于document的东西。getElementById(id)


The code is:

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}}}

#18


0  

There is a library on Github for tab support in your textareas by wjbryant: Tab Override

Github上有一个库,用于支持wjbryant: tab覆盖

This is how it works:

这就是它的工作原理:

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

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

#19


0  

Here's my version of this, supports:

这是我的版本,支持:

  • tab + shift tab
  • 选项卡+ shift选项卡
  • maintains undo stack for simple tab character inserts
  • 维护简单的选项卡字符插入的撤销堆栈
  • supports block line indent/unindent but trashes undo stack
  • 支持块线缩进/取消缩进,但撤销堆栈
  • properly selects whole lines when block indent/unindent
  • 当块缩进/不缩进时,正确地选择整行。
  • supports auto indent on pressing enter (maintains undo stack)
  • 支持按回车键自动缩进(保持撤销栈)
  • use Escape key cancel support on next tab/enter key (so you can press Escape then tab out)
  • 在next tab/enter键上使用Escape键取消支持(因此可以按Escape键然后按tab键退出)
  • Works on Chrome + Edge, untested others.
  • 适用于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).val();
					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>

#20


0  

Every input an textarea element has a onkeydown event. In the event handler you can prevent the default reaction of the tab key by using event.preventDefault() whenever event.keyCode is 9.

每个输入一个textarea元素都有一个onkeydown事件。在事件处理程序中,可以在事件发生时使用event. preventdefault()来防止选项卡键的默认反应。键码是9。

Then put a tab sign in the right 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

html

<textarea></textarea>

#21


0  

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

#22


-2  

If you really need tabs copy a tab from word or notepad and paste it in the text box where you want it

如果你真的需要制表符,从word或记事本中复制一个制表符,粘贴到你想要的文本框中

1 2 3

1 2 3

12 22 33

12 22 33

Unfortunately I think they remove the tabs from these comments though :) It will show as %09 in your POST or GET

不幸的是,我认为他们从这些评论删除了标签:)它将显示为%09在你的文章或得到