功用
产物需求:input 须要限定字符长度为 10。(中文 2 个字符英文 1 个字符)
斟酌场景:
input 中文题目
、
光标定位题目
、
字符串截取题目
。
完成思绪
完成上述需求需监听 3 个事宜:input
compositionupdate
compositionend
猎取光标位置
function getCursortPosition(obj) {
var cursorIndex = 0;
if (document.selection) {
// IE Support
obj.focus();
var range = document.selection.createRange();
range.moveStart("character", -obj.value.length);
cursorIndex = range.text.length;
} else if (obj.selectionStart || obj.selectionStart == 0) {
// another support
cursorIndex = obj.selectionStart;
}
return cursorIndex;
}
功用完成
<input type="type" name="" id="input" data-max="10" />
let flag = true; //设定全局变量在输入中文过程当中不实行赋值操纵
$("#input")
.on("input", function(e) {
setMaxlen(this);
})
.on("compositionupdate", function() {
flag = false;
})
.on("compositionend", function() {
flag = true;
setMaxlen(this);
});
/**
* @param {object} el DOM元素
*/
function setMaxlen(el) {
let val = $(el).val(), //猎取value
maxLen = $(el).data("max"), //猎取限定输入的最大值
len = val.replace(/[^\x00-\xff]/g, "**").length, //猎取input长度
startLen = getCursortPosition(el), //猎取光标位置
endLen = val.substring(startLen).replace(/[^\x00-\xff]/g, "**").length; //光标背面有几个字符(盘算后的)
if (flag && len > maxLen) {
let num = maxLen - endLen,//求出光标前面盈余的字符长度
str = val.substring(0, maxLen - endLen);//截取长度
while (str.replace(/[^\x00-\xff]/g, "**").length > num) {//因触及中文,轮回截取
if (str.length === 0) {
str = "";
break;
}
str = str.substring(0, str.length - 1);
}
$(el).val(str + val.substring(startLen));//设置value
//设置完value后须要从新设置下光标的位置。
let newStrLen = $(el).val().length,//猎取设置完value后的长度
setEnd = val.substring(startLen).length;//猎取原input光标后有几个字符
el.setSelectionRange(newStrLen - setEnd, newStrLen - setEnd);//设置光标位置
}
}