效果图
//HTML <div class="post_form"> <span class="left">和大家分享一点新鲜事吧?</span> <span class="right">可以输入<strong>140</strong>个字</span> <textarea class="post_textarea"></textarea> <input type="button" class="post_button" value="发布" /> </div>
//CSS #main .left { float:left; color:#666; font-size:14px; font-weight:bold; } #main .right { float:right; color:#ccc; font-size:13px; } #main .right strong { font-family:Constantia,Georgia; color:#049; font-size:22px; padding:0 5px; position:relative; top:-2px; } #main .right strong.red { color:red; } #main .post_textarea { 632px; height:80px; border:1px solid #ddd; background:#fff; resize:none; padding:8px; color:#666; font-size:16px; box-shadow:1px 1px 1px #dcdcdc inset; } #main .post_button { float:right; width: 90px; font-size:14px; font-weight:bold; margin-top:5px; }//JS//字数计算
//计算方法为 中文字算一个字,英文,数组,算半个字
$('.post_textarea').on('keyup',check_num);
$('.post_textarea').on('focus',function() {
setTimeout(function() {
check_num();
},50);
});
$('.post_textarea').on('blur',check_num);
function check_num() {
var total = 280;//140*2
var temp = 0;
var result_num = 140;
var length = $('.post_textarea').val().length;
if(length > 0) {
for(var i=0;i<length;i++) {
if($('.post_textarea').val().charCodeAt(i) > 255)
temp +=2;
else
temp++;
}
result_num = parseInt((total - temp) / 2);
}
if(result_num >= 0)
$('span.right').html('可以输入<strong>'+result_num+'</strong>个字');
else
$('span.right').html('已经超过了<strong class="red">'+result_num+'</strong>个字');
}