如何使用IMask创建支持可选负号的小时输入掩码?
解决IMask中负号前缀可选的问题
我用IMask实现了小时输入掩码,原配置如下:
var maskOptions = { overwrite: true, autofix: true, mask: 'HH:MM', blocks: { HH: { mask: IMask.MaskedRange, placeholderChar: 'HH', from: 0, to: 23, maxLength: 2 }, MM: { mask: IMask.MaskedRange, placeholderChar: 'MM', from: 0, to: 59, maxLength: 2 } } };
想要添加可选的负号前缀,于是修改配置将掩码设为[S]HH:MM并新增S块,但负号变成了强制输入,达不到可选效果。
解决方案
IMask里的方括号[]用于转义特殊字符,并非表示可选。要实现可选前缀,需用?后缀标记块为可选,或用括号()定义可选组。
修改后的正确配置:
var maskOptions = { overwrite: true, autofix: true, mask: 'S?HH:MM', // 用?标记S块为可选 blocks: { S: { mask: IMask.MaskedEnum, enum: ['-'], maxLength: 1, minLength: 0, // 允许该块为空 lazy: true // 自动跳过未输入的可选块,优化输入体验 }, HH: { mask: IMask.MaskedRange, placeholderChar: 'HH', from: 0, to: 23, maxLength: 2 }, MM: { mask: IMask.MaskedRange, placeholderChar: 'MM', from: 0, to: 59, maxLength: 2 } } };
关键说明:
S?表示S块为可选,用户可自主选择输入或不输入负号- S块的
minLength:0确保该块可以为空,配合?实现可选效果 lazy: true让光标自动跳过未输入的可选块,提升输入流畅度
另外,也可以用括号语法(S)HH:MM替代S?HH:MM,两者效果一致,可根据习惯选择。
内容的提问来源于stack exchange,提问作者Guilherme do Valle
相关产品推荐
相关产品推荐

