Html 文本区域的最大长度在 IE 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9109313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:13:45  来源:igfitidea点击:

Maxlength for text area doesn't work in IE

htmlasp.net-mvc-3

提问by Infant Dev

I am trying to limit the number of characters entered in a textarea as shown:

我试图限制在 textarea 中输入的字符数,如下所示:

<div>
 @Html.TextAreaFor(x => x.StudentName, new { @maxlength = "1000" })
</div>

This works fine in Firefox and Chrome but the maxlength attribute doesn't work in IE. How do I do that??

这在 Firefox 和 Chrome 中工作正常,但 maxlength 属性在 IE 中不起作用。我怎么做??

采纳答案by Darin Dimitrov

The maxlengthattribute is not standard for <textarea>in HTML 4.01. It is defined in HTML5though but I guess IE doesn't implement it. To make it work across all browsers you could use javascript. Here's an example.

maxlength属性<textarea>在 HTML 4.01 中不是标准的。虽然它是在 HTML5定义的,但我猜 IE 没有实现它。为了让它在所有浏览器上工作,你可以使用 javascript。这是一个例子

回答by Walter Stabosz

Here is my jQuery based solution. Works well in IE9, a little wonky in IE8.

这是我基于 jQuery 的解决方案。在 IE9 中运行良好,在 IE8 中有点不稳定。

// textarea event handler to add support for maxlength attribute
$(document).on('input keyup', 'textarea[maxlength]', function(e) {
    // maxlength attribute does not in IE prior to IE10
    // http://stackoverflow.com/q/4717168/740639
    var $this = $(this);
    var maxlength = $this.attr('maxlength');
    if (!!maxlength) {
        var text = $this.val();

        if (text.length > maxlength) {
            // truncate excess text (in the case of a paste)
            $this.val(text.substring(0,maxlength));
            e.preventDefault();
        }

    }

});

http://jsfiddle.net/hjPPn/

http://jsfiddle.net/hjPPn/

link for IE8: http://jsfiddle.net/hjPPn/show

IE8 链接:http: //jsfiddle.net/hjPPn/show

Native Browser Support

本机浏览器支持

Also, in case you're wondering which browsers do support maxlength: https://caniuse.com/#search=maxlength

另外,如果您想知道哪些浏览器确实支持maxlengthhttps: //caniuse.com/#search=maxlength

回答by erdomester

You can use javascript as well, which is way easier:

您也可以使用 javascript,这样更简单:

<textarea  name="question" cols="100" rows="8" maxlength="500px" onKeyPress="return ( this.value.length < 1000 );"></textarea>

回答by Sunil Soundarapandian

Use the following Jquery - for eg, if you want to restrict the length to 48

使用以下 Jquery - 例如,如果您想将长度限制为 48

$("textarea").keypress(function(e){
    var lengthF = $(this).val();

    if (lengthF.length > 48){
        e.preventDefault();
    }
});