我對上面的代碼有了一些改進。代碼的問題在於,您無法在輸入字段內導航。例如。您的值爲'100.00 |'當前光標在最後(用|表示)。如果按左鍵,它將跳轉到prev輸入字段,而不是將插入符號移動一個位置爲'100.0 | 0'。
爲了做到這一點,您需要使用e.target.selectionStart檢查當前插入符的位置。但是,您還需要prev插入位置,否則無法識別脫字符號是否從1到0(不跳),或者脫字符號已經在0,並且用戶再次向左按(跳轉)。
我添加的另一個更改是隻考慮具有類tableInput的輸入字段。如果你想排除一些領域。
function(e){
var charPos = e.target.selectionStart;
var strLength = e.target.value.length;
var prevPos = $(this).data('prevPos');
if(e.which==39){
//only go right if we really reached the end, that means the prev pos is the same then the current pos
if(charPos==strLength && (prevPos ==null || prevPos == charPos)){
$(this).closest('td').next().find('input.tableInput').focus();
$(this).data('prevPos',null);
}else{
$(this).data('prevPos',charPos);
}
}else if(e.which==37){
//only go left if we really reached the beginning, that means the prev pos is the same then the current pos
if(charPos == 0 && (prevPos ==null || prevPos == charPos)){
$(this).closest('td').prev().find('input.tableInput').focus();
$(this).data('prevPos',null);
}else{
$(this).data('prevPos',charPos);
}
}else if(e.which==40){
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input.tableInput').focus();
$(this).data('prevPos',null);
}else if(e.which==38){
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input.tableInput').focus();
$(this).data('prevPos',null);
}
});
來源
2014-03-12 11:05:18
Ben
什麼是您的HTML看起來像。我想你不會遵循正確的表格結構。 –
替代鏈接:https://jonlabelle.com/snippets/view/html/navigate-html-text-input-fields-with-arrow-keys – Paolo