小编典典

如何为输入占位符的各个部分设置样式?

html

是否可以为输入占位符的各个部分设置样式?一个例子:

请在这里输入 还请注意,您只能输入一次


阅读 373

收藏
2020-05-10

共1个答案

小编典典

您不能使用标准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;
}

是的,有很多代码,但是给您一些样式上的灵活性。

演示:http//jsfiddle.net/dfsq/xD5Lq/

UPD但是存在一个问题(感谢@AlexG进行报告)。输入值后,输入失去焦点,占位符将再次出现在该值的顶部。有两种方法可以解决此问题。第一个是再次使用:invalid伪类的纯CSS,它也需要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>
2020-05-10