最近項(xiàng)目需求有個地方需要給客戶添加備注信息晃听,不是計算機(jī)出身的我一開始就被字、字符能扒、字節(jié)這些概念難住了,既然要做一個可以現(xiàn)用的demo辛润,那還是順便科普一下字见秤、字符、字節(jié)的區(qū)別好了乎澄,系統(tǒng)學(xué)習(xí)。
html結(jié)構(gòu)
<label for="inputNote">備注:</label>
<textarea name="" id="inputNote" class="note" onkeyup="checkWord(this);" onmouseup="checkWord(this)"></textarea>
<div id="hasInput" style="display:none;">你已輸入<span id="wordCheck">0</span>/1000個字</div>
css樣式
textarea {
/*設(shè)置是否顯示滾動條*/
overflow-y: hidden;
height: 208px;
width: 265px;
/*禁止文本框拖動放大縮小*/
resize: none;
font-size: 15px;
padding-left: 10px;
}
.taFocus {
border:0;
color: #b94a48;
box-shadow: 0 0 3px 3px rgba(185,74,72,.6)
}
.taFocus:focus {
/*去除文本框 focus 時的藍(lán)色 outline */
outline:-webkit-focus-ring-color auto 0;
}
.note {
/*使文字和文本框頂部對齊*/
vertical-align: top;
}
js腳本
/**
* textarea 檢測字?jǐn)?shù)及限制提醒
* checkWord [檢查字符數(shù)]
* getStrleng [獲取字符數(shù)長度]
* 這里一個數(shù)字一個英文一個符號
*/
var maxstrlen = 1000;
var taLimit = $('#inputNote');
var hasInput = $('#hasInput');
var wck = $('#wordCheck');
function checkWord(c) {
var str = c.value;
myLen = str.length;
console.log(myLen);
hasWrite = 1000 - Math.floor((maxstrlen - myLen));
if(myLen > maxstrlen) {
c.value = str.substring(0, 1000);
} else {
if(parseInt(hasWrite) >= 950 && parseInt(hasWrite) < 1000 ) {
hasInput.show();
wck.html(hasWrite).css('color',"#666");
taLimit.removeClass('taFocus');
} else {
taLimit.removeClass('taFocus');
wck.css('color','#666');
hasInput.hide();
}
if (parseInt(hasWrite) >= 1000 ) {
hasInput.show();
wck.html(hasWrite).css('color',"red");
taLimit.addClass('taFocus');
}
}
}
最終效果
未達(dá)到1000字符數(shù)的效果
達(dá)到1000字符數(shù)的效果