如何使用新的html5属性控制p标签内的字符数,contenteditable =“true”?
我发现了如何用textarea做到这一点:
http://jsfiddle.net/timur/47a7A/ (工作)
但是我怎么能用p标签呢?
http://jsfiddle.net/47a7A/133/ (不工作)
HTML
<p id="textarea" maxlength="99" contenteditable="true">This content is editable with a max character count of 99.</p>
<div id="textarea_feedback"></div>
JQUERY
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
答案 0 :(得分:3)
<p>
个元素没有值。这适用于input
,textarea
等
您想使用text()
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').text().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
答案 1 :(得分:0)
@PaulRoub答案的问题是,如果超过字符限制,则插入符光标会移动到文本的开头。我使用jquery caret插件解决了这个问题。以下代码说明了使用id ="#text_area"
<script src="~/Scripts/jquery.caret.js"></script>
<script type="text/javascript">
var limit = 4000;
var $chars_left = limit - $('#text_area').text().length;
$('#char_limit').text($chars_left); //char_limit is span element that is used as a counter
$('#text_area').on('input', function (e)
{
var $char = $('#text_area').text().length;
$chars_left = limit - $char;
$('#char_limit').text($chars_left);
if ($char > 4000)
{
var $text = $('#text_area').text().substr(0, 3999);
$('#char_limit').text(0);
$('#text_area').html($text);
$('#text_area').caret(3999); //here is jquery.caret plugin that remain the position of the cursor
}
})
</script>