<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/jquery/jquery-1.10.2.min_65682a2.js"></script>
</head>
<body>
<input id="test" oninput="limitWordLen(this,3)"/>
<script type="text/javascript">javascript
/**
* <br>方 法 描 述:用於限制輸入的字符長度
* <br>參 數 說 明:
* obj:當前對象
* len:可輸入字符長度
* isDiff:是否區分中英文 true:區分 false:不區分 默認爲false 若爲true,則英文佔一個字符 中文佔兩個字符 若爲false,都佔一個字符
* 調 用 方 式: <input id="test" oninput="limitWordLen(this,3,true)"/>
* <br>創 建 人:jinzhaoqiang
* <br>建立時間:2018/6/19 16:45
* <br>修改備註:無
*/
function limitWordLen(obj,len,isDiff){
var str = $(obj).val();
if (typeof(len)!='number' || len <= 0){
if ($(obj).attr('preVal')) $(obj).val($(obj).attr('preVal')); //使用上一次的合法值
else $(obj).val('');
return false;
}
var isDiffIn = false;
if(typeof(isDiff)=='boolean')
isDiffIn = isDiff;
var length;
if (typeof(length = strlen(str,isDiffIn))!='number' || length>len) { //知足必定的條件不讓繼續輸入
if ($(obj).attr('preVal')) $(obj).val($(obj).attr('preVal')); //使用上一次的合法值
else $(obj).val('');
return false;
}
eval("$(obj).attr('preVal',$(obj).val())")
return true;
}html
function strlen(obj,isDiff){
var isDiffIn = false;
if (typeof(isDiff)=='boolean') isDiffIn = isDiff;
var str = obj;
var len = 0;
for (var i=0; i<str.length; i++) {
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
len++;
}
else {
if (isDiffIn)
len+=2;
else
len++;
}
}
return len;
} java
</script>
</body>
</html>jquery