示例http://dabblet.com/gist/5859946
如果您有一个长占位符,默认输入的宽度不足以显示所有占位符文本。
e.g。
<input placeholder="Please enter your name, address and shoe size">
如果没有设置固定宽度,最好没有javascript,您可以设置输入以显示所有占位符文本吗?
答案 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-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%
,则它将与父宽度匹配,该父宽度已经与占位符匹配。
注意事项
这个想法不是很容易获得,这个解决方案也不是。您应该为输入添加标签,而不要依赖占位符本身作为标签。
答案 3 :(得分:0)
我想到的解决方法:
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"