如何在ASP.NET中将文本框的宽度设置为与MaxLength相同

Joh*_*ams 5 asp.net textbox html-table maxlength width

有没有办法可以限制文本框的宽度等于MaxLength属性?在我的情况下,文本框控件放在表格单元格中,就像在此片段中一样:

<td class=TDSmallerBold style="width:90%">
        <asp:textbox id="txtTitle" runat="server"
            CausesValidation="true"
            Text="Type a title here..be concise but descriptive. Include price."
            ToolTip="Describe the item with a short pithy title (most important keywords first). Include the price. The title you provide here will be the primary text found by search engines that index Zipeee content." 
            MaxLength="60"
            Width="100%">
        </asp:textbox>
Run Code Online (Sandbox Code Playgroud)

(我知道我不应该使用HTML表来控制布局......另一个主题是肯定的)但是有没有办法将实际宽度限制为键入框中允许的最大字符数?

Mat*_*man 3

它不会很精确,因为字符的宽度可能会有所不同。但如果您真的对此很认真,您可以使用一些 Javascript (jQuery) 来完成。步骤是:

  • 在屏幕外创建一个跨度(顶部:-1000px 或其他)
  • 确保跨度与文本框具有相同的样式/类
  • 用 60 个字符填充范围
  • 使用 jQuery 测量跨度的宽度
  • 将该宽度应用于文本框

这是一种类似于您在 Facebook 上看到的自动扩展文本区域的技术,例如: http: //james.padolsey.com/javascript/jquery-plugin-autoresize/

(在这种情况下,您是水平而不是垂直地进行操作。)

如果您需要真正的代码,请告诉我,我会尽力而为。