jquery – 使用箭头键导航HTML表

前端之家收集整理的这篇文章主要介绍了jquery – 使用箭头键导航HTML表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用 HTML表创建了一个非常基本的电子表格.它完美无缺,但用户必须使用鼠标点击每个< td>为了编辑它.我正在使用jQuery捕获click事件并显示一个对话框来编辑它.我希望用户能够使用箭头键导航到每个单元格,单元格css背景更改以指示焦点,单击Enter键将触发jQuery对话框事件.我正在使用jQuery 1.9.

这里基本上是我的jsfiddle.

如何保存当前选定的单元格,以便在使用鼠标单击单元格,然后使用箭头键时,它将从“当前”单元格导航?

谢谢.

解决方法

下面是一个使用onkeydown事件并使用prevIoUsElementSibling和nextElementSibling属性的vanilla JavaScript解决方案.

https://jsfiddle.net/rh5aoxsL/

使用tabindex的问题在于,您无法像在Excel中那样导航,您可以远离电子表格本身.

HTML

  1. <table>
  2. <tbody>
  3. <tr>
  4. <td id='start'>1</td>
  5. <td>2</td>
  6. <td>3</td>
  7. <td>4</td>
  8. </tr>
  9. <tr>
  10. <td>5</td>
  11. <td>6</td>
  12. <td>7</td>
  13. <td>8</td>
  14. </tr>
  15. <tr>
  16. <td>9</td>
  17. <td>10</td>
  18. <td>11</td>
  19. <td>12</td>
  20. </tr>
  21. <tr>
  22. <td>13</td>
  23. <td>14</td>
  24. <td>15</td>
  25. <td>16</td>
  26. </tr>
  27. </tbody>
  28. </table>

CSS

  1. table {
  2. border-collapse: collapse;
  3. border: 1px solid black;
  4. }
  5. table td {
  6. border: 1px solid black;
  7. padding: 10px;
  8. text-align: center;
  9. }

JavaScript

  1. var start = document.getElementById('start');
  2. start.focus();
  3. start.style.backgroundColor = 'green';
  4. start.style.color = 'white';
  5.  
  6. function dotheneedful(sibling) {
  7. if (sibling != null) {
  8. start.focus();
  9. start.style.backgroundColor = '';
  10. start.style.color = '';
  11. sibling.focus();
  12. sibling.style.backgroundColor = 'green';
  13. sibling.style.color = 'white';
  14. start = sibling;
  15. }
  16. }
  17.  
  18. document.onkeydown = checkKey;
  19.  
  20. function checkKey(e) {
  21. e = e || window.event;
  22. if (e.keyCode == '38') {
  23. // up arrow
  24. var idx = start.cellIndex;
  25. var nextrow = start.parentElement.prevIoUsElementSibling;
  26. if (nextrow != null) {
  27. var sibling = nextrow.cells[idx];
  28. dotheneedful(sibling);
  29. }
  30. } else if (e.keyCode == '40') {
  31. // down arrow
  32. var idx = start.cellIndex;
  33. var nextrow = start.parentElement.nextElementSibling;
  34. if (nextrow != null) {
  35. var sibling = nextrow.cells[idx];
  36. dotheneedful(sibling);
  37. }
  38. } else if (e.keyCode == '37') {
  39. // left arrow
  40. var sibling = start.prevIoUsElementSibling;
  41. dotheneedful(sibling);
  42. } else if (e.keyCode == '39') {
  43. // right arrow
  44. var sibling = start.nextElementSibling;
  45. dotheneedful(sibling);
  46. }
  47. }

猜你在找的jQuery相关文章