0

问题:

如何使用新的 html5 属性 contenteditable="true" 控制 ap 标签内的字符数?


我已经找到了如何使用 textarea 执行此操作:http:
//jsfiddle.net/timur/47a7A/ (正在工作)

但是我将如何使用 ap 标签执行此操作?
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>

查询

$(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');
    });
});
4

2 回答 2

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');
    });
});

工作示例:http ://codepen.io/paulroub/pen/Hfymr

于 2013-09-19T22:00:55.087 回答
0

@PaulRoub 答案的问题是插入符号光标移动到文本的开头,如果它超过字符的限制。我使用jquery caret插件解决了这个问题。以下代码说明了 div 元素的 4000 个字符的限制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>
于 2014-08-25T15:48:13.853 回答