/*
字符串字节长度
*/
function getByteLength(){
var str = arguments[0];
return str.match(/[^ -~]/g) == null ? str.length : obj.value.length + str.match(/[^ -~]/g).length;
}
/*
截取子字符串,len为字节长度
*/
function subStringByteLength(field,len){
var disLen=len;
if(!disLen){
disLen=10;
}
for(var i=0;i<field.length&&i<disLen;i++){
if(field.charCodeAt(i)<0 || field.charCodeAt(i)>255){
disLen--;//每遇到一个双字节字符截取长度减少1
}
}
if(field.length > disLen){
return field.substring(0,disLen);
}else{
return field;
}
}
/*
程度控制
*/
function textAreaCtrl()
{
var x = document.getElementsByTagName('textarea');
for (var i=0;i<x.length;i++)
{
x[i].onpropertychange = textCount;
x[i].onkeypress = dokeypress;
x[i].onpaste = dopaste;
}
}
function textCount(len){
var obj = event.srcElement;
var a_limit = 500
if(arguments.length >0)
{
a_limit =len
}
var length = getByteLength(obj.value)
if (length > a_limit) {
obj.value = subStringByteLength(obj.value,a_limit);
}
}
function dokeypress()
{
var key = event.keyCode
if(!( ((key >= 48) && (key <= 57)) ||
((key >= 65) && (key <= 90)) ||
((key >= 97) && (key <= 122)) ||
(key == 13) ||
(key == 95) ||
(key == 40) ||
(key == 41) ||
(key == 32) ||
(key == 8)
)){
window.event.keyCode = 0;
}
}
function dopaste()
{
if(clipboardData.getData('text') != null && clipboardData.getData('text') != ''){
clipboardData.setData('text',clipboardData.getData('text').replace(/[^一-龥w]/g,''));
}
}
字符串字节长度
*/
function getByteLength(){
var str = arguments[0];
return str.match(/[^ -~]/g) == null ? str.length : obj.value.length + str.match(/[^ -~]/g).length;
}
/*
截取子字符串,len为字节长度
*/
function subStringByteLength(field,len){
var disLen=len;
if(!disLen){
disLen=10;
}
for(var i=0;i<field.length&&i<disLen;i++){
if(field.charCodeAt(i)<0 || field.charCodeAt(i)>255){
disLen--;//每遇到一个双字节字符截取长度减少1
}
}
if(field.length > disLen){
return field.substring(0,disLen);
}else{
return field;
}
}
/*
程度控制
*/
function textAreaCtrl()
{
var x = document.getElementsByTagName('textarea');
for (var i=0;i<x.length;i++)
{
x[i].onpropertychange = textCount;
x[i].onkeypress = dokeypress;
x[i].onpaste = dopaste;
}
}
function textCount(len){
var obj = event.srcElement;
var a_limit = 500
if(arguments.length >0)
{
a_limit =len
}
var length = getByteLength(obj.value)
if (length > a_limit) {
obj.value = subStringByteLength(obj.value,a_limit);
}
}
function dokeypress()
{
var key = event.keyCode
if(!( ((key >= 48) && (key <= 57)) ||
((key >= 65) && (key <= 90)) ||
((key >= 97) && (key <= 122)) ||
(key == 13) ||
(key == 95) ||
(key == 40) ||
(key == 41) ||
(key == 32) ||
(key == 8)
)){
window.event.keyCode = 0;
}
}
function dopaste()
{
if(clipboardData.getData('text') != null && clipboardData.getData('text') != ''){
clipboardData.setData('text',clipboardData.getData('text').replace(/[^一-龥w]/g,''));
}
}
本文介绍了一种使用JavaScript实现的文本控制方法,包括获取字符串的字节长度、根据字节长度截取字符串、限制文本框输入及粘贴内容的过滤等功能。这些实用的函数可以帮助开发者更好地控制用户输入,确保数据的有效性和格式的一致性。
1297

被折叠的 条评论
为什么被折叠?



