Html仅在表单中的输入占位符字段中的颜色(*)符号

Bar*_*raa 6 html css placeholder html-input

我有以下代码:

<input id="firstName" name="fname" type="text" maxlength="50" placeholder="First Name *" required>
Run Code Online (Sandbox Code Playgroud)

如何将占位符值中的(*)符号着色为红色而不用其他文本着色(作为名字文本)?

任何帮助深表感谢!

谢谢!人

Has*_*ami 5

一种可能的选择,可以使用:valid伪类的需要 <input>,使绝对定位的同级元素消失-其被用作输入下一个占位符.

因此,我们可以在绝对定位的元素上使用::before/ ::afterpseudo-elements来更改伪占位符的颜色.

.input-wrapper {
  display: inline-block;
  position: relative;
}

.input-wrapper input {
  background: transparent;
  border: 1px solid #999;
}

.input-wrapper input:valid + .placeholder {
  display: none;
}

.input-wrapper .placeholder {
  position: absolute;
  top: 1px;
  left: 2px;
  z-index: -1;
}

.input-wrapper .placeholder::before {
  content: attr(data-placeholder);
  color: #999;
}

.input-wrapper .placeholder::after {
  content: " *";
  color: tomato;
}
Run Code Online (Sandbox Code Playgroud)
<div class="input-wrapper">
  <input id="firstName" name="fname" type="text" maxlength="50" required>
  <span class="placeholder" data-placeholder="First Name"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

值得注意的:valid是IE10 +支持伪类.


Jac*_*ray 3

不幸的是,无法更改输入中某些文本的颜色:(您可以尝试使用 div contenteditable

<div class="input" contenteditable>First Name <span style="color:red;">*</span></div>
Run Code Online (Sandbox Code Playgroud)

然后,您必须使用 JS 添加和删除占位符:

$(function(){
    $('.input').focus(function(){
        $(this).html('');
    });
    $('.input').blur(function(){
       if($(this).html()=='') this.innerHTML='First Name <span style="color:red;">*</span>';
    });
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle 演示