我的HTML。
<div id="text" contenteditable="true" ></div>
我的Jquery
count = 212
$("#text").keydown(function(e){
if(e.keyCode === 8){
if(count === 212){
return;
}
count = count + 1;
}else{
count = count - 1;
}
});
但没有工作.. 当我使用鼠标选择 并按回空格(删除), 我的计数值不匹配
答案 0 :(得分:1)
尝试使用此代码进行字符计数操作:
HTML
<div id="txt" contenteditable="true" ></div>
<span id="count"></span>
JS:
$(document).ready(function(){
$('#txt').keyup(function(){
alert("hello");
var el=$(this);
alert(el.text().length);
$('#count').text(el.text().length);
});
});
CSS:
#txt
{
width:137px;
height:100px;
background-color:black;
color:white;
}
#count
{
width:55px;
background-color:blue;
height:15px;
color:white;
}
这里提供DEMO
作为参考
答案 1 :(得分:0)
您可以使用length
的{{1}}值,请参阅下面的代码
text
答案 2 :(得分:0)
为什么不使用HTML maxlength?
http://jsfiddle.net/yne738q6/1/
<input type='text' class='count' maxlength='212' />
$('.count').keyup(function(e){
console.log($('.count').val().length);
});
它永远不会超过212个字符。
答案 3 :(得分:0)
如果你想把它变成一个小的jQuery插件,你可以改编自下面的代码(它显示元素上方的字符数):
(function($) {
$.fn.countChar = function() {
return this.each(function() {
var $elem = $(this);
var $label = $("<div></div>").insertBefore($elem);
$elem.on("focus keyup", function(e) {
e.preventDefault();
$label.html($elem.text().length);
});
});
};
}(jQuery));
请参阅此处的示例:http://jsbin.com/deloc/3/