Input can only enter 20 bytes
Input can only enter 20 bytes
by xiaomin
HTML
<div class="name-body">
<input type="text" id="name">
<strong class="numberMain"><span class="numberReal">0</span>/10</strong>
</div>
SCSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.name-body{
color:#fff;
#name{
width:500px;
height:20px;
outline:none
}
}
JavaScript
var name = $("#name")
$("#name").on('input propertychange',function(){
var codeLength = getLength($(this).val()),
length = Math.floor(codeLength/2)
$('.numberReal').html(length)
})
$("#name").on('compositionend',function(){
var codeLength= getLength($(this).val()),
length= Math.floor(codeLength/2),
newStr= '',
newCodeLength= 0
if(length>10){
//获取截取字节长度之后的字符串
var arr =$(this).val().split('')
for(var value of arr){
newCodeLength += getLength(value)
newStr+=value
if(newCodeLength >=20){
$(this).val(newStr)
$('.numberReal').html(Math.floor(getLength($(this).val())/2))
break
}
}
}
});
/**
*获取字符串的字节长度
*/
function getLength(str)
{
var realLength = 0;
for (var i = 0; i < str.length; i++)
{
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128)
realLength += 1;
else
realLength += 2;
}
return realLength;
}