如何设置输入宽度以匹配占位符文本宽度

时间:2013-06-25 16:34:02

标签: css html5 placeholder

示例http://dabblet.com/gist/5859946

如果您有一个长占位符,默认输入的宽度不足以显示所有占位符文本。

e.g。

<input placeholder="Please enter your name, address and shoe size">

如果没有设置固定宽度,最好没有javascript,您可以设置输入以显示所有占位符文本吗?

4 个答案:

答案 0 :(得分:29)

这可以通过javascript设置size =占位符长度来完成:

input.setAttribute('size',input.getAttribute('placeholder').length);

这是一个代码,用于所有输入: http://jsfiddle.net/KU5kN/

答案 1 :(得分:6)

如果有人想在jQuery中使用它,那么代码就在下面。此外,如果接受的答案中不存在placeholder属性,您将收到错误,这些错误在下面的jQuery示例中也会得到解决。

$("input[placeholder]").each(function () {
        $(this).attr('size', $(this).attr('placeholder').length);
    });

答案 2 :(得分:4)

我接受了上述部分之一的评论中提出的Avner Solomon的解决方案。

您需要一个div元素,其中包裹着一个input和另一个包含标签的div元素:

<div class="input-container">
     <!-- this element is hidden from display and screen readers. -->
     <div class="input-hidden-label" 
          aria-hidden="true">
       Your placeholder text
     </div>

     <input class="input" 
            type="text" 
            placeholder="Your placeholder text"/>
</div>

假设input-hidden-labelinput的字体样式相同,您将在输入旁边看到一行文本。文本的长度将与输入的长度相同,或者增加或减少几个像素。

然后您可以应用以下样式:

.input-container {
  display: inline-block;
  margin-bottom: 2em;
}

.input {
  display: inline;
  width: 100%;
  font-size: 16px;
  font-family: Times;
}

.input-hidden-label {
  height: 0;
  visibility: hidden;
}

这通过给标签height: 0并删除visibility来隐藏标签。但是,width仍然存在。包含div和标签的input与其最长子级的width相匹配。如果然后将input设置为width: 100%,则它将与父宽度匹配,该父宽度已经与占位符匹配。

See this fiddle.

注意事项

这个想法不是很容易获得,这个解决方案也不是。您应该为输入添加标签,而不要依赖占位符本身作为标签。

答案 3 :(得分:0)

我想到的解决方法:

  • 使用与占位符相同的文本制作一个span元素。
  • 测量span元素的宽度。
  • 将输入设置为span元素的宽度。
  • 隐藏跨度元素。不显示任何内容均不起作用,请使用其他方法。

http://jsfiddle.net/Timar/cwLp3rbo/

var input = document.getElementById('input-1');

// measure width of same text as placeholder
var placeholder =  document.getElementById('input-1-placeholder');


input.style.width = placeholder.offsetWidth + "px"