是否可以对输入占位符的各个部分进行样式设置?一个例子:
请输入此处。另请注意,您只能进入一次.
你不能用标准做到这一点placeholder
属性。我将详细介绍另一种方法,即使用输入元素周围的一些包装器来制作自定义占位符。
HTML
<div class="placeholder-wrap">
<input type="text" name="userName" />
<span class="placeholder">
This is a <b class="important">placeholder</b>
</span>
</div>
CSS:
.placeholder-wrap {
margin: 20px;
display: inline-block;
position: relative;
background: #FFF;
}
.placeholder-wrap .placeholder {
position: absolute;
top: 50%;
left: 5px;
color: #888;
margin-top: -.5em;
line-height: 1em;
z-index: 9;
overflow: hidden;
white-space: nowrap;
width: 100%;
}
.placeholder-wrap input {
background-color: transparent;
border: 1px #999 solid;
padding: 4px 6px;
position: relative;
z-index: 10;
}
.placeholder-wrap input:focus + .placeholder {
display: none;
}
是的,有相当多的代码,但为您提供了一定的样式灵活性。
Demo: http://jsfiddle.net/dfsq/xD5Lq/
UPD。然而有一个问题(感谢@AlexG 的报告)。输入值并且输入失去焦点后,占位符会再次出现在值的顶部。有两种方法可以解决这个问题。第一个是纯CSS,再次使用:invalid
伪类,这还需要required
输入属性:
.placeholder-wrap {
display: inline-block;
position: relative;
background: #FFF;
overflow: hidden;
}
.placeholder-wrap .placeholder {
position: absolute;
top: 50%;
left: 5px;
color: #888;
margin-top: -.5em;
line-height: 1em;
z-index: 9;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
}
.placeholder-wrap input {
background-color: transparent;
border: 1px #999 solid;
padding: 4px 6px;
position: relative;
z-index: 10;
}
.placeholder-wrap input:focus + .placeholder,
.placeholder-wrap input[required]:valid + .placeholder,
.placeholder-wrap input.not-empty + .placeholder {
display: none;
}
input {width: 300px;}
.important {color: brown;}
<p>CSS fix</p>
<div class="placeholder-wrap">
<input type="text" name="userName" required />
<span class="placeholder">
This is a <b class="important">placeholder</b> long text goes here
</span>
</div>
<p>Javascript fix</p>
<div class="placeholder-wrap">
<input type="text" name="userName"
onchange="this.className = this.value
? this.className + ' not-empty'
: this.className.replace(/\bnot-empty\b/, '')"
/>
<span class="placeholder">
This is a <b class="important">placeholder</b> long text goes here
</span>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)