Javascript:检测textarea是否已满 [英] Javascript: detect textarea to be full

查看:75
本文介绍了Javascript:检测textarea是否已满的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测textarea何时变满以创建分页效果。但是,使用.length属性将不起作用,因为长字会跳转到新行。

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   |

所以最终发生的事情是,在.length属性到达之前,textarea总是耗尽空间textarea限制。有没有其他方法来检测textarea丰满度? Jquery解决方案也很好。谢谢。

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.

推荐答案

您可以尝试检查textarea中是否出现了滚动条。 此处是一种简单的方法。最初使滚动条比您想要显示的最终高度短一行,然后在按键检查滚动条是否出现,然后等待输入下一个空格。输入空格字符后,请执行以下操作:
1.删除空格字符,
2.增加textarea高度一行逗留(滚动条消失),
3.创建一个新的textarea并将焦点转移到新的textarea。

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:

标记

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

这篇关于Javascript:检测textarea是否已满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆