|
|
@@ -19,39 +19,90 @@ export function gainFocus(e: string, data: any[]) {
|
|
|
// 创建事件处理函数
|
|
|
function createTapEvent(input: any, index: number) {
|
|
|
return function() {
|
|
|
+ // 保存当前光标位置
|
|
|
+ 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);
|
|
|
+
|
|
|
// 确保数据更新
|
|
|
if(Array.isArray(data) && index < data.length) {
|
|
|
// 使用splice方法更新数组,确保 Vue 3 能够检测到变化
|
|
|
data.splice(index, 1, formattedValue);
|
|
|
}
|
|
|
- }, 100);
|
|
|
+ }, 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;
|
|
|
+ }
|
|
|
console.log(data);
|
|
|
return data;
|
|
|
}
|
|
|
|
|
|
-// 更改格式
|
|
|
+// 更改格式 - 智能格式化日期时间字符串
|
|
|
function disposeData(str) {
|
|
|
- var value = str.split("");
|
|
|
- if (value.length == 4) {
|
|
|
- value.splice(4, 0, "-");
|
|
|
+ // 先移除所有分隔符,只保留数字
|
|
|
+ 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 (value.length == 7) {
|
|
|
- value.splice(7, 0, "-");
|
|
|
+
|
|
|
+ // 添加日期
|
|
|
+ if (digits.length > 6) {
|
|
|
+ result += '-';
|
|
|
+ result += digits.substring(6, 8);
|
|
|
}
|
|
|
- if (value.length == 10) {
|
|
|
- value.splice(10, 0, " ");
|
|
|
+
|
|
|
+ // 添加小时
|
|
|
+ if (digits.length > 8) {
|
|
|
+ result += ' ';
|
|
|
+ result += digits.substring(8, 10);
|
|
|
}
|
|
|
- if (value.length == 13) {
|
|
|
- value.splice(13, 0, ":");
|
|
|
+
|
|
|
+ // 添加分钟
|
|
|
+ if (digits.length > 10) {
|
|
|
+ result += ':';
|
|
|
+ result += digits.substring(10, 12);
|
|
|
}
|
|
|
- if (value.length == 16) {
|
|
|
- value.splice(16, 0, ":");
|
|
|
+
|
|
|
+ // 添加秒
|
|
|
+ if (digits.length > 12) {
|
|
|
+ result += ':';
|
|
|
+ result += digits.substring(12, 14);
|
|
|
}
|
|
|
- return value.join("");
|
|
|
-}
|
|
|
+
|
|
|
+ return result;
|
|
|
+}
|