【问题标题】:Specify input field width base on character size根据字符大小指定输入字段宽度
【发布时间】:2013-10-18 20:55:57
【问题描述】:

我正在尝试设置输入字段以确保用户可以看到输入字段的总长度。

例如

<input size='60' type='text'/>

我希望用户一次看到总共 60 个字符,而不是看到总长度被截断到 50 左右。

我无法指定输入字段的宽度,因为无法知道宽度是多少(可以是短的也可以是长的,并且是动态的)。

http://jsfiddle.net/j2KrZ/4/

谁能知道如何做到这一点?谢谢!

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

如果您使用Monospaced font(每个字符的宽度固定),则输入框宽度应最多可容纳 60 个字符。在 IE10、Firefox 22 和 Chrome 30.0.1599.69 中测试

用于解决此问题的等宽字体示例:

<input size='60' maxlength='60' style="font-family: 'Courier New', Courier, monospace;" type='text' value='123456789012345678901234567890123456789012345678901234567890'/>

【讨论】:

  • 我不知道旧浏览器是如何计算输入宽度的,但你应该自己测试一下,因为它可能没问题。
  • 这也适用于旧浏览器。盒子有时可能有点太大,但这应该是可以接受的。
【解决方案2】:

如果您正在寻找动态输入宽度,您可以使用事件处理程序:

$("input").keyup(function(){
    $(this).width($("input").val().length * w); // w = width of a single char (if monospace), otherwise max char width    
});

【讨论】:

    【解决方案3】:

    一种有点笨拙的方法,它遍历每个 input 元素,创建一个 div,将 input 的 CSS 复制到创建的 div,应用 float(允许其宽度为由其内容决定),然后将该宽度分配给input(并删除创建的元素):

    $('input[type="text"]').css('width', function (){
        // gets the applied style as it appears once rendered in the page:
        var styles = window.getComputedStyle(this, null),
        // temporary element:
            tmp = document.createElement('div');
    
        // creates a textNode child for the div, containing the value of the input:
        tmp.appendChild(document.createTextNode(this.value));
    
        // sets the style attribute of the div to those styles of the input
        // (note that 'tmp.style = styles['cssText']' did not work, sadly):
        tmp.setAttribute('style', styles['cssText']);
    
        // floating, so the width is determined by the content, not the parent-width:
        tmp.style.float = 'left';
    
        // appends the div to the body:
        document.body.appendChild(tmp);
    
        // gets the rendered width of the div and stores it:
        var w = window.getComputedStyle(tmp, null).width;
    
        // removes the div, since it's no longer required:
        tmp.parentNode.removeChild(tmp);
    
        // returns the width, to set the width of the input element:
        return w;
    });
    

    JS Fiddle demo.

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 2016-05-14
      • 2011-07-23
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多