Html Color only (*) symbol in input placeholder field in form

允我心安 提交于 2019-12-01 04:23:50

Unfortunately, it isn't possible to change the color of certain text in a input :( you can try to use a contenteditable div:

<div class="input" contenteditable>First Name <span style="color:red;">*</span></div>

Then, you have to add and remove the placeholder with JS:

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

JSFiddle Demo

One possible option could be using :valid pseudo-class for the required <input> to make the absolutely positioned sibling element disappear — which is used as a placeholder under the input.

So, we can use ::before/::after pseudo-elements over the absolutely positioned element to change the color of our pseudo-placeholder.

.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;
}
<div class="input-wrapper">
  <input id="firstName" name="fname" type="text" maxlength="50" required>
  <span class="placeholder" data-placeholder="First Name"></span>
</div>

It's worth noting that :valid pseudo-class is supported in IE10+.

enigma

You probably can't, like that. The best way to do this would be something like this SO answer: Multiple font colors in an Input tag

In essence, a second div is put over the input field, allowing for the change in colour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!