dataformat.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // 获取 dom 方法 - 给输入框添加格式化处理,并更新响应式数据
  2. export function gainFocus(elementId: string, formObj: any, fieldName: string) {
  3. const container = document.getElementById(elementId);
  4. if (!container) {
  5. return;
  6. }
  7. const inputs = container.getElementsByTagName("input");
  8. for (let i = 0; i < inputs.length; i++) {
  9. const input = inputs[i];
  10. if ((input as any)._formattedBound) continue;
  11. (input as any)._formattedBound = true;
  12. input.addEventListener("input", createTapEvent(input));
  13. }
  14. function createTapEvent(input: any) {
  15. return function() {
  16. // 防止 dispatchEvent 触发递归
  17. if ((input as any)._isFormatting) return;
  18. (input as any)._isFormatting = true;
  19. const cursorPosition = input.selectionStart;
  20. const oldValue = input.value;
  21. const digitsBeforeCursor = oldValue.substring(0, cursorPosition).replace(/[^0-9]/g, '').length;
  22. setTimeout(() => {
  23. const formattedValue = disposeData(input.value);
  24. input.value = formattedValue;
  25. const newCursorPosition = getCursorPosition(formattedValue, digitsBeforeCursor);
  26. input.setSelectionRange(newCursorPosition, newCursorPosition);
  27. // 触发 input 事件让 Vue 的 v-model 自动捕获值的变化
  28. const event = new Event('input', { bubbles: true });
  29. input.dispatchEvent(event);
  30. // 重置标志位
  31. (input as any)._isFormatting = false;
  32. }, 0);
  33. };
  34. }
  35. function getCursorPosition(formattedValue: string, digitCount: number) {
  36. let count = 0;
  37. for (let i = 0; i < formattedValue.length; i++) {
  38. if (count === digitCount) {
  39. return i;
  40. }
  41. if (/[0-9]/.test(formattedValue[i])) {
  42. count++;
  43. }
  44. }
  45. return formattedValue.length;
  46. }
  47. }
  48. // 更改格式 - 智能格式化日期时间字符串
  49. function disposeData(str) {
  50. // 先移除所有分隔符,只保留数字
  51. const digits = str.replace(/[^0-9]/g, '');
  52. // 按照固定位置重新添加分隔符
  53. // 格式:YYYY-MM-DD HH:mm:ss
  54. let result = '';
  55. // 添加年份(最多4位)
  56. result += digits.substring(0, 4);
  57. // 添加月份
  58. if (digits.length > 4) {
  59. result += '-';
  60. result += digits.substring(4, 6);
  61. }
  62. // 添加日期
  63. if (digits.length > 6) {
  64. result += '-';
  65. result += digits.substring(6, 8);
  66. }
  67. // 添加小时
  68. if (digits.length > 8) {
  69. result += ' ';
  70. result += digits.substring(8, 10);
  71. }
  72. // 添加分钟
  73. if (digits.length > 10) {
  74. result += ':';
  75. result += digits.substring(10, 12);
  76. }
  77. // 添加秒
  78. if (digits.length > 12) {
  79. result += ':';
  80. result += digits.substring(12, 14);
  81. }
  82. return result;
  83. }