我有一个简单的html textarea。现在,如果单击其中的选项卡,它将转到下一个字段。我想让标签按钮缩进几个空格。我怎样才能做到这一点?感谢。
答案 0 :(得分:112)
从类似问题的其他答案中大量借用(下面发布)......
$(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
答案 1 :(得分:45)
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,并将在页面上的所有textareas上启用选项卡功能。
答案 2 :(得分:34)
正如其他人所写,您可以使用JavaScript捕获事件,阻止默认操作(以便光标不会移动焦点)并插入制表符。
但是,禁用默认行为会导致无法使用鼠标将焦点移出文本区域。盲人用户使用键盘与网页互动,没有别的 - 他们看不到鼠标指针做任何有用的事情,所以它是键盘或什么也没有。 Tab键是导航文档的主要方式,尤其是表单。覆盖tab键的默认行为将使盲人用户无法将焦点移动到下一个表单元素。
因此,如果您正在为广大受众群体撰写网站,我建议您不要在没有引人注目的原因的情况下执行此操作,并为盲目用户提供某种替代方案将它们困在textarea。
答案 3 :(得分:29)
对于它的价值,这是我的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>
最新版Chrome,Firefox,Internet Explorer和Edge中的Testest。
答案 4 :(得分:9)
我无法快速尝试在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>
答案 5 :(得分:7)
这两种方法都是直截了当的,并且不会失去撤消功能(Ctrl + Z)的最新更改。
#!/bin/bash
SCRIPT_PATH="xx.sh"
for x in {001..031}; do
"$SCRIPT_PATH" /data/raw/"$x"_AE data/processed/"$x"_AE 5 --info
done
有关$('#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));
}
});
的更多信息:
答案 6 :(得分:6)
基于@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;
}
});
答案 7 :(得分:6)
此解决方案允许像典型代码编辑器一样在整个选择中进行制表,并取消选择该选择。但是,当没有选择时,我还没有想出如何实现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>
答案 8 :(得分:6)
你必须编写JS代码来捕获TAB键按下并插入一堆空格。类似于JSFiddle的东西。
检查jquery fiddle:
<强> 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');
}
});
答案 9 :(得分:3)
基于人们不得不在这里说出答案的所有内容,它只是keydown(不是keyup)和preventDefault()的组合+在插入符号处插入制表符。类似的东西:
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
insertAtCaret('txt', '\t')
}
早期的答案有一个工作的jsfiddle,但它在keydown上使用了alert()。如果您删除此警报,则它不起作用。我刚刚添加了一个函数来在textarea中的当前光标位置插入一个制表符。
这是一个有效的jsfiddle: http://jsfiddle.net/nsHGZ/
答案 10 :(得分:2)
我看到这个问题没有解决。我对此进行了编码,并且工作得非常好。 它在光标索引处插入一个列表。不使用jquery
var1 = %{someprop: 123}
IO.inspect var1
答案 11 :(得分:2)
按住ALT并从数字键盘按0,9。它适用于google-chrome
答案 12 :(得分:2)
这是我的版本,支持:
$(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;
});
});
&#13;
textarea
{
width: 100%;
height: 100px;
tab-size: 4;
}
&#13;
<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>
&#13;
答案 13 :(得分:1)
以上答案全部擦除撤消历史记录。对于那些寻找不能做到这一点的解决方案的人来说,我花了最后一小时为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。
答案 14 :(得分:0)
作为上述kasdega代码的一种选择,您可以在当前光标处插入字符,而不是将选项卡附加到当前值。这样做的好处是:
所以替换
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void checkButton_Click(object sender, RoutedEventArgs e)
{
Build getModel = new Build();
getModel.MotherModel(inputBox.Text);
}
}
使用
// set textarea value to: text before caret + tab + text after caret
$(this).val($(this).val().substring(0, start)
+ "\t"
+ $(this).val().substring(end));
答案 15 :(得分:0)
我发现最简单的方法是在现代浏览器中使用原始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) + " " + value.slice(selectionEnd);
codebox.setSelectionRange(selectionStart+2, selectionStart+2)
}
});
</script>
请注意,为简单起见,我在此代码段中使用了许多ES6功能,您可能需要在部署它之前(使用Babel或TypeScript)对其进行转换。
答案 16 :(得分:0)
我制作了一个你可以使用任何你喜欢的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>
答案 17 :(得分:-1)
在Github上有一个库,可以通过wjbryant在你的textareas中获得标签支持:Tab Override
这是它的工作原理:
// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');
// enable Tab Override for all textareas
tabOverride.set(textareas);
答案 18 :(得分:-1)
textarea元素的每个输入都有一个onkeydown事件。在事件处理程序中,只要event.keyCode为9,就可以使用 event.preventDefault()来阻止Tab键的默认反应。
然后在正确的位置放置一个标签符号:
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>
答案 19 :(得分:-1)
我必须创建一个相同的函数,使用起来很简单,只需将此代码复制到您的脚本并使用: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}}}
答案 20 :(得分:-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
}
});
答案 21 :(得分:-1)
简单的独立脚本:
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;
}
}
}
答案 22 :(得分:-1)
尝试这个简单的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();
答案 23 :(得分:-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;
}
}
答案 24 :(得分:-3)
如果你真的需要标签从word或记事本复制标签并将其粘贴到你想要的文本框中
1 2 3
12 22 33
不幸的是我认为他们从这些评论中删除了标签:) 它将在POST或GET中显示为%09