You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.6 KiB

2 years ago
  1. // 通过绑定输入框的 class 来实现enter 代替 tab 的功能
  2. /*
  3. 示例
  4. import { getKeyUp } from '../../utlis/getKeyUp'
  5. created() {
  6. getKeyUp('enterToTab')
  7. }
  8. */
  9. export function getKeyDown(className){
  10. //当前页面监视键盘输入 onkeyup /onkeydown
  11. document.onkeydown = function(e) {
  12. //e.keyCode === 13
  13. if(e.key == 'Enter'){
  14. // 阻止文本框的换行
  15. if(window.event){
  16. window.event.returnValue = false;
  17. }else{
  18. e.preventDefault(); //for firefox
  19. }
  20. // 标记当前组件为true
  21. if(e.target.tagName === 'INPUT'){
  22. e.target.autofocus = true;
  23. }else if(e.target.tagName === 'TEXTAREA'){
  24. e.target.autofocus = true;
  25. }else{
  26. e.target.firstChild.autofocus = true;
  27. }
  28. // 获取所有需要定位的组件
  29. let arr = document.querySelectorAll("."+className);
  30. let index2 = -1;
  31. arr.forEach((i,index) => {
  32. if(i.querySelectorAll("input")[0]){
  33. if(i.querySelectorAll("input")[0].autofocus){
  34. index2 = index;
  35. }
  36. }else if(i.querySelectorAll("textarea")[0]){
  37. if(i.querySelectorAll("textarea")[0].autofocus){
  38. index2 = index;
  39. }
  40. }else{
  41. // 暂无其他
  42. }
  43. })
  44. // 超出返回第一个组件
  45. if(index2 + 1 >= arr.length){
  46. index2 = -1;
  47. }
  48. // 聚焦到下一个组件中
  49. if(arr[index2 + 1].querySelectorAll("input")[0]){
  50. if(arr[index2 + 1].querySelectorAll("input")[0].type === 'hidden'){
  51. arr[index2 + 1].querySelectorAll("input")[0].parentElement.focus();
  52. }else{
  53. arr[index2 + 1].querySelectorAll("input")[0].focus();
  54. }
  55. }else if(arr[index2 + 1].querySelectorAll("textarea")[0]){
  56. arr[index2 + 1].querySelectorAll("textarea")[0].focus();
  57. }else{
  58. // 暂无其他
  59. }
  60. // 重置当前组件为false
  61. if(e.target.tagName === 'INPUT'){
  62. e.target.autofocus = false;
  63. }else if(e.target.tagName === 'TEXTAREA'){
  64. e.target.autofocus = false;
  65. }else{
  66. e.target.firstChild.autofocus = false;
  67. }
  68. }
  69. }
  70. }