文本区字符限制

IT技术 javascript html textarea cross-browser
2021-01-19 08:49:20

我希望能够限制 textarea 中的字符数。我使用的方法在 Google Chrome 中效果很好,但在 Firefox 中很慢,在 IE 中不起作用。

Javascript:

function len(){
  t_v=textarea.value;
  if(t_v.length>180){
    long_post_container.innerHTML=long_post;
    post_button.className=post_button.className.replace('post_it_regular','post_it_disabled');
    post_button.disabled=true;
  }
  else{
    long_post_container.innerHTML="";
    post_button.className=post_button.className.replace('post_it_disabled','post_it_regular');
    post_button.disabled=false;
  }
  if(t_v.length>186){
        t_v=t_v.substring(0,186);
    }
}

HTML:

<textarea id="user_post_textarea" name="user_post_textarea" cols="28" rows="1"  onkeypress="len();" onkeyup="len();"></textarea>

body 元素底部的 Javascript:

textarea=document.getElementById('user_post_textarea');
6个回答

我找到了一个很好的解决方案,它在浏览器支持的情况下使用maxlength属性,并在不支持的浏览器中回退到不显眼的 javascript pollyfill。

感谢@Dan Tello 的评论,我修复了它,因此它也适用于 IE7+:

HTML:

<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>

Javascript:

function maxLength(el) {    
    if (!('maxLength' in el)) {
        var max = el.attributes.maxLength.value;
        el.onkeypress = function () {
            if (this.value.length >= max) return false;
        };
    }
}

maxLength(document.getElementById("text"));

演示

没有这样的事情作为一个minlength在HTML5属性。
对于以下输入类型:numberrangedatedatetimedatetime-localmonthtimeweek尚未完全支持)使用minmax属性。

不适用于即“无效的'in'操作数:预期的对象”
2021-03-26 08:49:20
@Nileshpatel 我已经在 IE7+ 中测试了我的演示(这是一个用于 IE 测试全屏版本),控制台中没有错误,并且字符限制正常工作。
2021-03-29 08:49:20
问题是:如果遇到限制,它不再接受任何按键,因此您甚至不能退格最后一句话。您必须使用上下文菜单来删除某些内容。
2021-04-09 08:49:20
@DanTello 带有新演示的新代码。适用于 IE7+ 和其他浏览器。没有签入IE6-。
2021-04-12 08:49:20
您编辑的方法似乎在 IE 7 + 8 中失效。不过,第一个似乎有效。
2021-04-13 08:49:20

这完全未经测试,但它应该可以满足您的需求。

更新:这里有一个 jsfiddle 可以查看。似乎正在工作。关联

您可以将它粘贴到一个 js 文件中,并在您的 jquery 引用之后引用它。然后你会这样称呼它..

$("textarea").characterCounter(200);

对正在发生的事情的简要说明..

在每个 keyup 事件中,该函数都会检查按下了哪种类型的键。如果可以接受,计数器将检查计数,修剪任何超出的部分,并在达到限制后阻止任何进一步输入。

该插件也应该处理粘贴到目标中。

  ; (function ($) {
        $.fn.characterCounter = function (limit) {
            return this.filter("textarea, input:text").each(function () {
                var $this = $(this),
                  checkCharacters = function (event) {

                      if ($this.val().length > limit) {

                          // Trim the string as paste would allow you to make it 
                          // more than the limit.
                          $this.val($this.val().substring(0, limit))
                          // Cancel the original event
                          event.preventDefault();
                          event.stopPropagation();

                      }
                  };

                $this.keyup(function (event) {

                    // Keys "enumeration"
                    var keys = {
                        BACKSPACE: 8,
                        TAB: 9,
                        LEFT: 37,
                        UP: 38,
                        RIGHT: 39,
                        DOWN: 40
                    };

                    // which normalizes keycode and charcode.
                    switch (event.which) {

                        case keys.UP:
                        case keys.DOWN:
                        case keys.LEFT:
                        case keys.RIGHT:
                        case keys.TAB:
                            break;
                        default:
                            checkCharacters(event);
                            break;
                    }   

                });

                // Handle cut/paste.
                $this.bind("paste cut", function (event) {
                    // Delay so that paste value is captured.
                    setTimeout(function () { checkCharacters(event); event = null; }, 150);
                });
            });
        };
    } (jQuery));
在您的示例中,当按住某个键时,textarea 不会修剪字符数,直到释放该键。我想要像@webarto 这样的东西,但这会过滤掉 [DEL] 和 [BACKSPACE]。
2021-03-23 08:49:20
您的示例允许在半秒后删除该字符之前放置另一个字符,但这并不是我真正想要的。我编辑了@Christian Sciberras 提供的答案以过滤必要的键码,效果很好!
2021-03-23 08:49:20
@inquisitive:这可以通过将 if ($this.val().length > limit) 更改为 ($this.val().length >= limit) 的行轻松解决。我希望上帝你不会像 Christian 的例子那样内嵌编写它,并且至少将它移动到一个单独的 js 文件中。
2021-03-31 08:49:20

使用 textarea 的 maxlength 属性可以解决问题......简单的 html 代码......不是 JS 或 JQuery 或需要服务器端检查......

较旧的浏览器不支持 maxlength。对于 IE,它必须是版本 10。
2021-04-04 08:49:20

这适用于键盘和粘贴,当您几乎达到限制时,它会将文本着色为红色,当您过去时将其截断并提醒您编辑文本,您可以这样做。

var t2= /* 文本区域引用*/

t2.onkeyup= t2.onpaste= function(e){
    e= e || window.event;
    var who= e.target || e.srcElement;
    if(who){
        var val= who.value, L= val.length;
        if(L> 175){
            who.style.color= 'red';
        }
        else who.style.color= ''
        if(L> 180){
            who.value= who.value.substring(0, 175);
            alert('Your message is too long, please shorten it to 180 characters or less');
            who.style.color= '';
        }
    }
}

我认为这样做可能比大多数人想象的要容易!

试试这个:

var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.        
    if (yourTextArea.length < 10 || yourTextArea.length > 400) {
        alert("The field must have no less than 10 and no more than 400 characters.");
        return false;
    }

请让我知道这很有用。如果是这样,请投票!谢谢!

丹尼尔