Use Arrow Keys to Jump Between Input Text Field
效果可以看这个 Demo。
这样就解决了一个核心问题,可以实现仿照 Excel 的单元格移动,接下来就是考虑怎样实现复制粘贴了,这个有点难。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<script> $(document).ready(function(){ $('input:text:first').focus(); $('input:text').bind("keydown", function(e) { var n = $("input:text").length; if (e.which == 13) { //Enter key e.preventDefault(); //to skip default behavior of the enter key var tdindex = $(this).closest('td').index(); $(this).closest('tr').next().next().find('td:eq('+tdindex+')').find('input').focus(); } }); $('input').keyup(function(e){ var charPos = e.target.selectionStart; var strLength = e.target.value.length; var prevPos = $(this).data('prevPos'); //e.preventDefault(); if(e.which==40){ //Down Arrow //return which column the td is, startiing with 0 var tdindex = $(this).closest('td').index(); $(this).closest('tr').next().next().find('td:eq('+tdindex+')').find('input').focus(); }else if(e.which==38){ //Up Arrow var tdindex = $(this).closest('td').index(); $(this).closest('tr').prev().prev().find('td:eq('+tdindex+')').find('input').focus(); }else if(e.which==39){ //Right Arrow if(charPos==strLength && (prevPos ==null || prevPos == charPos)){ $(this).closest('td').next().find('input').focus(); $(this).data('prevPos',null); }else{ $(this).data('prevPos',charPos); } }else if(e.which==37){ if(charPos == 0 && (prevPos ==null || prevPos == charPos)){ $(this).closest('td').prev().find('input').focus(); $(this).data('prevPos',null); }else{ $(this).data('prevPos',charPos); } } }); }); </script> |