Javascript:检测文本区域已满
我正在尝试检测文本区域何时变满以创建分页效果。但是,使用 .length 属性不起作用,因为长单词会“跳”到新行。
| I like to dooo| displays as | I like to |
| oooodle | | dooooooodle |
因此最终发生的情况是,在 .length 属性达到文本区域限制之前,文本区域总是耗尽空间。还有其他方法可以检测文本区域的填充度吗? Jquery 解决方案也很好。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试检查文本区域中是否出现滚动条。 这里是执行此操作的简单方法。最初使滚动条比您想要显示的最终高度短一行,然后在按键时检查滚动条是否已出现,然后等待输入下一个空格字符。输入空格字符后,立即执行以下操作:
1.删除空格字符,
2.增加文本区域高度一行徘徊(因此滚动条消失),
3. 创建一个新的文本区域并将焦点移至新的文本区域。
更新
这是一个演示。我稍微改变了我的方法,这是代码:
Markup
JS
CSS
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
JS
CSS
在运行时,您可以监听textarea的按键事件,将textarea.val()值传递到隐藏的
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.