效果图:
1、输入汉字
2、输入数字或英文
3、汉字数字混合
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta txt="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
background: #efefef;
}
.clsinp {
width: 100%;
height: 40px;
outline: none;
line-height: 40px;
font-size: 16px;
padding: 0 10px;
margin-top: 20px;
color: blue;
}
.clsmsg {
padding: 10px 10px;
}
.clsmsg span {
color: blue;
}
</style>
</head>
<body>
<div id="app">
<input v-model="txt" class="clsinp" maxlength="16" placeholder="请输入内容" type="text">
<div class="clsmsg">
<p>内容:<span>{{computedTxt}}</span></p>
<p>输入的字符个数:<span>{{computedCharLen}}</span></p>
<p>输入的字节个数:<span>{{computedByteLen}}</span></p>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="./vue2.5.1.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data() {
return {
txt: ''
}
},
// 后期代码在下面补充
methods: {
methodGetByteLen(str, len) {
if (this.computedByteLen <= len) {
return str
}
for (let i = Math.floor(len / 2); i < str.length; i++) {
if (str.substr(0, i).replace(/[^\x00-\xff]/g, '01').length >= len) {
return str.substr(0, Math.floor(i / 2) * 2) + '...'
}
}
}
},
computed: {
// 获取字符的个数
computedCharLen() {
return this.txt.length
},
// 获取字节的个数
computedByteLen() {
return this.txt.replace(/[^\x00-\xff]/g, '01').length
},
// 控制显示的内容
computedTxt() {
return this.methodGetByteLen(this.txt, 10)
}
}
})
</script>
转载自:https://segmentfault.com/a/1190000011681004