本文介绍了textarea字符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够限制textarea中的字符数。我使用的方法是非常适合谷歌Chrome浏览器,但它在Firefox中很慢,它不工作在IE。

I would like to be able to limit the number of characters in a textarea. The method I am using is works great for Google Chrome, but it is slow in Firefox, and it doesn't work in IE.

Javascript:

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>

身体元素底部的JavaScript:

Javascript at bottom of body element:

textarea=document.getElementById('user_post_textarea');


推荐答案

我发现一个很好的解决方案, =http://www.wufoo.com/html5/attributes/03-maxlength.html> maxlength 属性,如果浏览器支持它,并返回到一个不显眼的javascript pollyfill在不支持的浏览器。

I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.

感谢我已将其修复,以便在IE7 +中正常工作:

Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:

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"));

Demo

有作为HTML5中的 minlength 属性。

对于以下输入类型: number range date datetime datetime-local c>和(其中尚未完全支持)使用 min max 属性。

There is no such thing as a minlength attribute in HTML5.
For the following input types: number, range, date, datetime, datetime-local, month, time, and week (which aren't fully supported yet) use the min and max attributes.

这篇关于textarea字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:44