代码之家  ›  专栏  ›  技术社区  ›  Brian Ramsay

我可以在css中指定最大长度吗?

  •  92
  • Brian Ramsay  · 技术社区  · 16 年前

    <input type='text' id="phone_extension" maxlength="4" />
    
    8 回复  |  直到 16 年前
        1
  •  61
  •   edeverett    16 年前

    号码

    CSS是用于样式的。

    这就是为什么。

        2
  •  119
  •   user151323    16 年前

    不需要。这需要在HTML中完成。如果需要,您可以使用Javascript设置该值。

        3
  •  11
  •   Community Mohan Dere    12 年前

    你可以像这样使用jQuery:

    $("input").attr("maxlength", 4)
    

    这是一个演示: http://jsfiddle.net/TmsXG/13/

        4
  •  6
  •   Charlie Gevious    16 年前

    我认为你不能,CSS应该描述页面的外观,而不是它的功能,所以即使你可以,也不是你应该如何使用它。

        5
  •  4
  •   JMP    16 年前

    没有CSS,没有。

        6
  •  3
  •   code_burgar    16 年前

    不使用CSS,但您可以使用JavaScript模拟和扩展/自定义所需的行为。

        7
  •  2
  •   Taylor Brown    8 年前

    正如其他人所回答的那样,目前还没有直接向CSS类添加maxlength的方法。

    然而,这种创造性的解决方案可以实现您想要的东西。

    我把jQuery放在一个名为maxLengths.js的文件中,我在网站上引用了它(ASP的site.master)

    运行该代码段以查看其运行情况,效果良好。

    jquery、css、html:

    $(function () {
        $(".maxLenAddress1").keypress(function (event) {
    
            if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */
                return false;
            } else {
                return true;
            }
    
        });
    });
    .maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <input type="text" class="maxLenAddress1" />

    使用此方法的优点是:如果确定需要在整个应用程序中推出或引入此类字段的最大长度,则可以在一个位置进行更改。对于客户代码、全名字段、电子邮件字段、应用程序中常见的任何字段的字段长度来说都很方便。

        8
  •  0
  •   Livius Rohit    11 年前

    使用 $("input").attr("maxlength", 4) 如果您使用的是jQuery版本<1.6 和 $("input").prop("maxLength", 4) 如果你使用的是jQuery 1.6+版本。