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

后端 未结 3 1415
无人及你
无人及你 2021-01-12 17:50

I have the following code:


相关标签:
3条回答
  • 2021-01-12 18:01

    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+.

    0 讨论(0)
  • 2021-01-12 18:08

    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

    0 讨论(0)
  • 2021-01-12 18:16

    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.

    0 讨论(0)
提交回复
热议问题