This effect is integrated into a function. This function accepts 3 parameters:
The first is the ID of the textarea or other text form;
The second is the ID of the displayed input content, which can be left blank;
The third one is the most input character, one Chinese character is 2 characters.
This is just a basic effect, and students are welcome to optimize and improve it.
To get the code, please view the source file of the demo
If you need to introduce external Js, you need to refresh to execute <script>
function lengthLimit(elem, showElem, max){
var elem = document.getElementById(elem);
var showElem = document.getElementById(showElem);
var max = max || 50;// 最大限度字符,汉字按两个字符计算
function getTextLength(str){// 获取字符串的长度 一个汉字为2个字符
return str.replace(/[^\x00-\xff]/g,"xx").length;
};
// 监听textarea的内容变化
if(/msie (\d+\.\d)/i.test(navigator.userAgent) == true) {// 区分IE
elem.onpropertychange = textChange;
}else{
elem.addEventListener("input", textChange, false);
}
function textChange(){// 内容变化时的处理
var text = elem.value;
var count = getTextLength(text);
if(count > max){// 文字超出截断
for(var i=0; i<text.length; i++){
if(getTextLength(text.substr(0, i)) >= max){
elem.value = text.substr(0, i);
if(showElem) showElem.innerHTML = elem.value;// 显示输出结果
break;
};
}
}else{
if(showElem) showElem.innerHTML = elem.value;// 显示输出结果
};
};
textChange();// 加载时先初始化
};
</script>]
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn