调用方式
$("#cdkey").formatCdkey({});
默认参数
{ separator:"-", //默认分隔符 splitLength:4, //分割长度 groupCount:5, //分隔符分隔的组数 isSetCase:true, //是否转换大小写 isToUpCase:true //true转换大写;false转换小写(isSetCase:true时生效) }
ps:separator仅支持单字符;
默认格式样例:F15A-D165-F168-94BF-A4T9
(function ($) { function containSpecial(s) { var containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/); return (containSpecial.test(s)); };$.fn.formatCdkey = function (options) { if (options.separator && options.separator.length > 1) { console.log("unsupport separator!"); return; }; var defaults = { separator : "-", //默认分隔符 splitLength : 4, //分割长度 groupCount : 5, //分隔符分隔的组数 isSetCase : true, //是否转换大小写 isToUpCase : true //转换大写 }; var opts = $.extend({}, defaults, options); var $this = $(this); var timeoutFlag; var maxLength = opts.splitLength * opts.groupCount + opts.groupCount - 1; $this.keyup(function (e) { clearTimeout(timeoutFlag); if (opts.isSetCase) { $this.val(opts.isToUpCase ? $this.val().toUpperCase() : $this.val().toLowerCase()); } var fixVal = function () { var regPrefix = ""; if (containSpecial(opts.separator)) { regPrefix = "\\"; }; var aval = $this.val().replace(new RegExp(regPrefix + opts.separator, "g"), ""); if (aval.length >= opts.splitLength) { var avalArray = aval.split(""); var newVal = ""; for (var i = 0; i < avalArray.length; i++) { if (i > 0 && (i + 1) % opts.splitLength == 0 && newVal.length <= maxLength) { newVal += (avalArray[i] + opts.separator); } else { newVal += avalArray[i]; } } //截取最大长度约束的字符长度 $this.val(newVal.substring(0, Math.min(newVal.length, maxLength))); }; }; if (e.keyCode == 8) { //删除键 timeoutFlag = setTimeout(function (){ fixVal(); }, 2000); return; }; fixVal(); }); }
})(jQuery);
$(document).ready(function () {
$("#cdkey").formatCdkey({});
});
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于