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

问题描述 投票:0回答:4
css html placeholder
4个回答
54
投票

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

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

这是一个针对所有输入进行剂量调整的代码: http://jsfiddle.net/KU5kN/


11
投票

以防万一有人想将其与 jQuery 一起使用,该代码如下。另外,如果接受的答案中不存在

placeholder
属性,您将收到错误,这在下面的 jQuery 示例中也得到了处理。

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

8
投票

我采用了 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-label
input
的字体样式相同,您将在输入旁边看到一行文本。文本将与输入的长度相同,增加或减少几个像素。

然后您可以应用这些样式:

.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%
,它将与父级宽度匹配,而父级宽度已经与占位符匹配。

看到这个小提琴。

注意事项

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


1
投票

我想到的解决方法:

  • 创建一个与占位符具有相同文本的 span 元素。
  • 测量跨度元素的宽度。
  • 将输入设置为 span 元素的宽度。
  • 隐藏跨度元素。显示none不行,请使用其他方法。

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"
© www.soinside.com 2019 - 2024. All rights reserved.