将textarea符号限制为可见部分 [英] Limit textarea symbols to visible part

查看:101
本文介绍了将textarea符号限制为可见部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我不希望滚动,我已经为它指定了行数列,而我希望该用户无法输入可能会出现滚动的字符。

当然,我可以设置溢出:隐藏但符号无论如何都会被输入。限制为字符数不是我的情况,因为不同的字符采用不同的宽度:例如W和1.我需要这种逻辑,因为在textarea中输入的数据用于某些打印报告,并且不可能在纸上滚动。 / p>

我发现只有两种可能的解决方案:



  1. 个字符的数量。并限制这个
    数字。这很粗糙。由于
    对于平均数量为
    的大字符的字符串而言比$平常多,所以
    仍然会隐藏一些数据。

  2. 使用
  3. 将输入的
    个字符呈现给某个单独的div并
    计算其宽度/高度。看来
    我会很慢,而不是
    ,确保这是正确的实现。

  4. >解决方案

您可以使用JavaScript来检查 scrollHeight ,如果大于原始高度,则截断文本直到它没有滚动了。代码为:

 函数CheckScroll(oTextarea){
if(oTextarea.scrollHeight> oTextarea.offsetHeight ){
while(oTextarea.scrollHeight> oTextarea.offsetHeight){
oTextarea.value = oTextarea.value.substr(0,oTextarea.value.length - 1);



$ / code>

并触发它:

 < textarea cols =15rows =3onkeyup =CheckScroll(this);平变化= CheckScroll(本); onpaste = CheckScroll(本); >< / textarea的> 

现场测试案例: http://jsfiddle.net/yahavbr/bNqVf/1/


Is there any way to limit textarea entered symbols to visible part only?

I don't want scrolling, I have specified number of rows column for it and I want that user could not enter so many characters that possible scrolling will appear.

Of course I could set overflow:hidden but symbols anyway will be entered. Limiting to the number of characters is not my case, because different character take different width: for example W and 1. I need this logic because data entered in textarea are used on some print report and there is no possibility for scrolling in paper.

I have found only 2 possible solutions:

  1. Use some average number of characters. And limit by this number. This is very rough. Because for strings with average number of big characters greater than usual it will still hide some data.

  2. Use rendering of entered characters to some separate div and calculate its width/height. Seem to me will be very slow and not sure this is the correct implementation.

解决方案

You can use JavaScript to check the scrollHeight and if bigger than the "original" height, truncate the text until it has no scroll anymore. Code for this would be:

function CheckScroll(oTextarea) {
    if (oTextarea.scrollHeight > oTextarea.offsetHeight) {
        while (oTextarea.scrollHeight > oTextarea.offsetHeight) {
            oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - 1);
         }
    }
}

And to trigger it:

<textarea cols="15" rows="3" onkeyup="CheckScroll(this);" onchange="CheckScroll(this);" onpaste="CheckScroll(this);"></textarea>

Live test case: http://jsfiddle.net/yahavbr/bNqVf/1/

这篇关于将textarea符号限制为可见部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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