美文网首页
jquery实现textarea字符限制

jquery实现textarea字符限制

作者: 爱鸽子的玉米君 | 来源:发表于2016-08-22 17:33 被阅读134次

最近项目需求有个地方需要给客户添加备注信息,不是计算机出身的我一开始就被字、字符、字节这些概念难住了,既然要做一个可以现用的demo,那还是顺便科普一下字、字符、字节的区别好了,系统学习。

html结构

<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 {
    /*设置是否显示滚动条*/
    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 时的蓝色 outline */
    outline:-webkit-focus-ring-color auto 0;
}
.note {
    /*使文字和文本框顶部对齐*/
    vertical-align: top;
}

js脚本

/**
 * textarea 检测字数及限制提醒
 * checkWord [检查字符数]
 * getStrleng [获取字符数长度]
 * 这里一个数字一个英文一个符号
 */
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');
        }
    }
}

最终效果

未达到1000字符数的效果 达到1000字符数的效果

相关文章

网友评论

      本文标题:jquery实现textarea字符限制

      本文链接:https://www.haomeiwen.com/subject/ktlgsttx.html