Javascript: detect textarea to be full

寵の児 提交于 2019-11-29 15:38:33
Majid Fouladpour

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

In runtime, you may listen to the key-press event of the textarea, pass the textarea.val() value into a hidden <pre id="mypre" style="display:none; "></pre>, then get mypre's width or even height $("#mypre").width(). It's your decision how you'll work with the "simulated" width/height.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!