Stack Overflow是如何实现字符计数器并显示“xyz characters left”的?
![enter image description here](https://istack.dev59.com/fZD01.webp)
可能是这样的(使用jQuery):
$('#txtbox').keypress(function() {
var max = 500;
var textLen = $(this).val().length;
var textLeft = max - textLen;
$('#charCount').text(
textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'
);
});
我知道不去看他们是如何做到的可能有些懒,但这里有一个可行的例子:http://jsfiddle.net/FishBasketGordo/hqex8/
HTML:
<textarea id="text" onkeyup="charCount(this);"></textarea>
<span id="chars"></span>
JS:
var maxChars = 500;
function charCount(el) {
document.getElementById('chars').innerText = maxChars - this.value.length;
}
没有经过测试,但这是基础。
.innerHTML
因为它是一个数字。节日快乐! - Lekensteyn这可以通过几种方式完成,但是这里有一些简单源代码的链接。了解SO如何做到这一点的唯一确定方法是查看他们压缩的JavaScript。
看看我网站上的这个页面http://www.bestvaluesolicitors.com/contact-us
查看JS - 您正在寻找此函数:
function ml(id,max,repeat){if($F(id).length>max){$(id).value=$F(id).substring(0,max);}$(id).next('div').update($F(id).length+' / '+max+' characters');if(repeat==true){setTimeout('ml("'+id+'",'+max+','+repeat+')',500);}}
本质上,它是一个计时器和计算textarea
中文本长度的组合。
document.getElementById('freddy').onkeypress =
document.getElementById('freddy').onkeyup =
document.getElementById('freddy').onkeydown = function(){
var count = this.value.length;
if(max < count){
this.value = this.value.substring(0,999);
return false;
}
setTimeout(function(){
document.getElementById('susan').innerHTML =
(max-count)+' characters left!';
},1);
};
这里是StackExchange的charCounter()方法的定义。它有点混淆,但如果你仔细研究,就可以找到逻辑:
charCounter: function(c) {
return this.each(function() {
var d = $(this).parents("form").find("span.text-counter");
var e = this;
var f = function() {
var j = c.min;
var l = c.max;
var k = c.setIsValid || function() {};
var h = e.value ? e.value.length : 0;
var i = h > l * .8 ? "supernova" : h > l * .6 ? "hot" : h > l * .4 ? "warm" : "cool";
var g = "";
if (h == 0) {
g = "enter at least " + j + " characters";
k(false);
} else {
if (h < j) {
g = j - h + " more to go..";
k(false);
} else {
g = l - h + " character" + (l - h != 1 ? "s" : "") + " left";
k(h <= l);
}
}
d.text(g);
if (!d.hasClass(i)) {
d.removeClass("supernova hot warm cool").addClass(i);
}
};
$(this).bind("blur focus keyup", a.DelayedReaction(f, 100, {
sliding: true
}).trigger);
});
}
而评论文本区域,例如,设置为以下内容(再次混淆):
var x = z.find("textarea");
x.charCounter({
min: 15,
max: 600,
setIsValid: A
});