gpt4 book ai didi

javascript - 如何在内容可编辑表中捕获键盘事件?

转载 作者:行者123 更新时间:2023-11-29 15:06:54 25 4
gpt4 key购买 nike

假设我有一个 HTML 表格:

  • 包含可编辑的单元格
  • 行跨度

在内容可编辑单元格中,可以按键盘上的“Enter”键,如果我想让用户只输入单行数据,这没有任何意义。

我想要的是,当用户在可编辑单元格上按下输入按钮时,它应该聚焦到最近的可编辑单元格(右/下)以进行新输入。

我应该如何解决问题?

<table>
<tr>
<th>Data 1</th>
<th>Data 2</th>
<th>Data 3</th>
<th>Data 4</th>
<th>Data 5</th>
<th>Data 6</th>
</tr>
<tr>
<td rowspan="3" contenteditable="true"><label><input type="radio" name="typeOf0" checked=""> <span>Radio 1</span> </label><br><label><input type="radio" name="typeOf0"> <span>Radio 2</span> </label><br></td>
<td rowspan="3" contenteditable="true">0</td>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
<td rowspan="3" contenteditable="true">0</td>
</tr>
<tr>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
</tr>
<tr>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
<td contenteditable="true">0</td>
</tr>
<tr></tr>
<tr>
</table>

最佳答案

诀窍是捕捉按键,并处理输入(键代码 13)。

您可以编辑@filemono 中已经提供的示例,以允许它与 enter 一起使用。

(function ($) {

$.fn.enableCellNavigation = function () {

var keys = {
left: 37,
up: 38,
right: 39,
down: 40,
enter: 13
};

// select all on focus
// works for input elements, and will put focus into
// adjacent input or textarea. once in a textarea,
// however, it will not attempt to break out because
// that just seems too messy imho.
this.find('input').keydown(function (e) {

// shortcut for key other than arrow keys
if ($.inArray(e.which, [keys.left, keys.up, keys.right, keys.down, keys.enter]) < 0) {
return;
}

var input = e.target;
var td = $(e.target).closest('td');
var moveTo = null;

switch (e.which) {

case keys.left:
{
if (input.selectionStart == 0) {
moveTo = td.prev('td:has(input,textarea)');
}
break;
}
case keys.right:
{
if (input.selectionEnd == input.value.length) {
moveTo = td.next('td:has(input,textarea)');
}
break;
}

case keys.up:
case keys.enter:
case keys.down:
{

var tr = td.closest('tr');
var pos = td[0].cellIndex;

var moveToRow = null;
if (e.which == keys.down || e.which == keys.enter) {
moveToRow = tr.next('tr');
} else if (e.which == keys.up) {
moveToRow = tr.prev('tr');
}

if (moveToRow.length) {
moveTo = $(moveToRow[0].cells[pos]);
}

break;
}

}

if (moveTo && moveTo.length) {

e.preventDefault();

moveTo.find('input,textarea').each(function (i, input) {
input.focus();
input.select();
});

}

});

};

})(jQuery);


// use the plugin
$(function () {
$('#people').enableCellNavigation();
});

关于javascript - 如何在内容可编辑表中捕获键盘事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59090963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com