【发布时间】:2014-03-26 08:42:51
【问题描述】:
是否可以为输入占位符的各个部分设置样式?一个例子:
请在此处输入。 还请注意,您只能输入一次。
【问题讨论】:
-
你应该提供一些你想要做什么的代码。占位符是什么意思?
-
@Metalskin
<input type="text" placeholder="...">
标签: html
是否可以为输入占位符的各个部分设置样式?一个例子:
请在此处输入。 还请注意,您只能输入一次。
【问题讨论】:
<input type="text" placeholder="...">
标签: html
你不能用标准的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;
}
是的,有不少代码,但在样式方面为您提供了一些灵活性。
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>
【讨论】:
如果您希望使用标准输入[type=text],则不可能。
您可能可以通过 div 创建“输入”并将 contenteditable 设置为 true。
<div contenteditable="true" id="input">
<strong>Please enter here.</strong> Please also be reminded that you can only enter once.</div>
用 css 重新创建它看起来像一个输入字段。
<style type="text/css">
#input {
border: 1px solid black;
width: 420px;
font-size: 12px;
font-family: Arial;
padding: 5px;
</style>
我已经上传了一个演示 here。
编辑:有人提到占位符文本没有被删除。一个简单的 jQuery 代码解决了这个问题。
$("#input").html("");
【讨论】: