我想要一个带有多个彩色文本的占位符。是否可以帮助我。
我有一个输入文本,其中占位符表示我是个好男孩。我想要颜色不同的好词。
不可以 ,无法为默认占位符着色,但是您可以创建类似于占位符的元素。因此,您可以为字母着色。这是默认占位符的解决方法。
请注意,我正在使用opacity: 0.5,您可以根据需要进行更改。
opacity: 0.5
HTML
.input-field { position: relative; display: inline-block; } .input-field > label { position: absolute; left: 0.5em; top: 50%; margin-top: -0.5em; opacity: 0.5; } .input-field > input[type=text]:focus + label { display: none; } .input-field > label > span { letter-spacing: -2px; } .first-letter { color: red; } .second-letter { color: blue; } .third-letter { color: orange; } .fourth-letter { color: green; } .fifth-letter { color: yellow; } <div class="input-field"> <input id="input-text-field" type="text"></input> <label for="input-text-field"> <span class="first-letter">H</span> <span class="second-letter">E</span> <span class="third-letter">L</span> <span class="fourth-letter">L</span> <span class="fifth-letter">O</span> </label> </div>
工作小提琴
更新:
:placeholder-shown
上面的小提琴有一个Bug ,当您在文本框中键入内容并单击外部时,占位符将再次出现在输入的文本上方。
因此,要使其完美,我们可以使用:placeholder-shown除chrome和firefox之外没有太多支持的工具。
这是代码:
.input-field { position: relative; display: inline-block; } .input-field > label { position: absolute; left: 0.5em; top: 50%; margin-top: -0.5em; opacity: 0.5; display: none; } .input-field > input[type=text]:placeholder-shown + label { display: block; } .input-field > label > span { letter-spacing: -2px; } .first-letter { color: red; } .second-letter { color: blue; } .third-letter { color: orange; } .fourth-letter { color: green; } .fifth-letter { color: yellow; } <div class="input-field"> <input id="input-text-field" type="text" placeholder=" "></input> <label for="input-text-field"> <span class="first-letter">H</span> <span class="second-letter">E</span> <span class="third-letter">L</span> <span class="fourth-letter">L</span> <span class="fifth-letter">O</span> </label> </div>
addListenerMulti(document.getElementById('input-text-field'), 'focus keyup', blurme); function blurme(e) { var element = e.currentTarget; element.classList[(element.value.length !== 0) ? "add" : "remove"]('hide-placeholder'); } function addListenerMulti(el, s, fn) { s.split(" ").forEach(function(e) { return el.addEventListener(e, fn, false) }); } .input-field { position: relative; display: inline-block; } .input-field > label { position: absolute; left: 0.5em; top: 50%; margin-top: -0.5em; opacity: 0.5; } .hide-placeholder + label { display: none; } .input-field > label > span { letter-spacing: -2px; } .first-letter { color: red; } .second-letter { color: blue; } .third-letter { color: orange; } .fourth-letter { color: green; } .fifth-letter { color: yellow; } <div class="input-field"> <input id="input-text-field" type="text"></input> <label for="input-text-field"> <span class="first-letter">H</span> <span class="second-letter">E</span> <span class="third-letter">L</span> <span class="fourth-letter">L</span> <span class="fifth-letter">O</span> </label> </div>