Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - Javascript: detect textarea to be full

I am trying detect when a textarea becomes full for creating pagination effect. Using the .length property will not work, however, because long words 'jump' to new lines.

| I like to dooo|     displays as  | I like to     | 
| oooodle       |                  | dooooooodle   |

So what ends up happening is that the textarea always runs out of space before the .length property reaches the textarea limit. Is there any other way to detect textarea fullness? Jquery solutions are fine as well. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try to check if scrollbars have appeared in your textarea. Here is a simple way to do this. Initially make the scrollbar one line shorter than the ultimate height you want to show, then on keypress check if scrollbars have appeared, then wait for the next space char to be entered. As soon as space char is entered do the following: 1. delete the space char, 2. increase the textarea height one line linger (so scrollbar disappears), 3. create a new textarea and move focus to the new textarea.

Update
Here is a demo. I changed my method a bit and this is the code:

Markup

<textarea class="paginate"></textarea>

JS

$('textarea.paginate').live('keydown', function() {

    // scrollbars apreared
    if (this.clientHeight < this.scrollHeight) {

        var words = $(this).val().split(' ');
        var last_word = words.pop();
        var reduced = words.join(' ');
        $(this).val(reduced);
        $(this).css('height', '65px');

        $(this).after('<textarea class="paginate"></textarea>');
        $(this).next().focus().val(last_word);

    }

});

CSS

.paginate { height: 60px; width: 200px; display: block;}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...