el-input框输入时(默认为半角字符),中文转全角字符、英文转半角字符
全角和半角的区别
效果图
代码
index.vue
<template>
<div>
<el-input style="width:240px;" @input="nameValue(input)" v-model="input" placeholder="请输入内容"></el-input>{{input}}
</div>
</template>
<script>
// 语言代码
const langCodeList = Object.freeze([
{ label: '大陆', value: 'CHI' },
{ label: '港澳', value: 'CHT' },
{ label: '英文', value: 'ENG' },
{ label: '葡文 ', value: 'POR' },
]);
export default {
data(){
return{
input:'',
}
},
methods:{
nameValue(val){ // 大陆和港澳名称,统称中文
if (k.LANG_CODE === 'CHI' || k.LANG_CODE === 'CHT') {
this.input = this.input ? this.ToDBC(this.input.trim().replace(/\s+/g, ' ')) : ''; // 中文转全角
}else{ // 英文和葡文名称对应的拼音字段为空,不转义
this.input = this.input ? this.ToCDB(this.input.trim().replace(/\s+/g, ' ')) : ''; // 英文转半角
}
},
ToDBC(txtstring) {
// 半角转全角
if (txtstring == null || txtstring == '' || txtstring == ' ') {
return '';
}
var tmp = '';
for (var i = 0; i < txtstring.length; i++) {
if (txtstring.charCodeAt(i) == 32) {
tmp += String.fromCharCode(12288);
} else if (txtstring.charCodeAt(i) == 160) {
// 处理下Unicode为160的特殊空格
tmp += String.fromCharCode(12288);
} else if (txtstring.charCodeAt(i) < 127) {
tmp += String.fromCharCode(txtstring.charCodeAt(i) + 65248);
} else {
tmp += String.fromCharCode(txtstring.charCodeAt(i));
}
}
return tmp;
},
ToCDB(str) {
// 全角转半角
var tmp = void 0;
if (str) {
tmp = '';
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) == 12288) {
tmp += String.fromCharCode(32);
} else if (str.charCodeAt(i) == 160) {
tmp += String.fromCharCode(32); // 处理下Unicode为160的特殊空格
} else if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
} else {
tmp += str[i];
}
}
} else {
tmp = str;
}
return tmp;
},
}
}
</script>