| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- // 获取 dom 方法 - 给输入框添加格式化处理,并更新响应式数据
- export function gainFocus(elementId: string, formObj: any, fieldName: string) {
- const container = document.getElementById(elementId);
- if (!container) {
- return;
- }
- const inputs = container.getElementsByTagName("input");
- for (let i = 0; i < inputs.length; i++) {
- const input = inputs[i];
- if ((input as any)._formattedBound) continue;
- (input as any)._formattedBound = true;
- input.addEventListener("input", createTapEvent(input));
- }
- function createTapEvent(input: any) {
- return function() {
- // 防止 dispatchEvent 触发递归
- if ((input as any)._isFormatting) return;
- (input as any)._isFormatting = true;
- const cursorPosition = input.selectionStart;
- const oldValue = input.value;
- const digitsBeforeCursor = oldValue.substring(0, cursorPosition).replace(/[^0-9]/g, '').length;
- setTimeout(() => {
- const formattedValue = disposeData(input.value);
- input.value = formattedValue;
- const newCursorPosition = getCursorPosition(formattedValue, digitsBeforeCursor);
- input.setSelectionRange(newCursorPosition, newCursorPosition);
- // 触发 input 事件让 Vue 的 v-model 自动捕获值的变化
- const event = new Event('input', { bubbles: true });
- input.dispatchEvent(event);
- // 重置标志位
- (input as any)._isFormatting = false;
- }, 0);
- };
- }
- function getCursorPosition(formattedValue: string, digitCount: number) {
- let count = 0;
- for (let i = 0; i < formattedValue.length; i++) {
- if (count === digitCount) {
- return i;
- }
- if (/[0-9]/.test(formattedValue[i])) {
- count++;
- }
- }
- return formattedValue.length;
- }
- }
- // 更改格式 - 智能格式化日期时间字符串
- function disposeData(str) {
- // 先移除所有分隔符,只保留数字
- const digits = str.replace(/[^0-9]/g, '');
- // 按照固定位置重新添加分隔符
- // 格式:YYYY-MM-DD HH:mm:ss
- let result = '';
- // 添加年份(最多4位)
- result += digits.substring(0, 4);
- // 添加月份
- if (digits.length > 4) {
- result += '-';
- result += digits.substring(4, 6);
- }
- // 添加日期
- if (digits.length > 6) {
- result += '-';
- result += digits.substring(6, 8);
- }
- // 添加小时
- if (digits.length > 8) {
- result += ' ';
- result += digits.substring(8, 10);
- }
- // 添加分钟
- if (digits.length > 10) {
- result += ':';
- result += digits.substring(10, 12);
- }
- // 添加秒
- if (digits.length > 12) {
- result += ':';
- result += digits.substring(12, 14);
- }
- return result;
- }
|