[removed] How to change color to only part of the string in an input field?

后端 未结 4 663
一个人的身影
一个人的身影 2020-12-22 03:55

I have an input field where I would like to have the characters turn red after the 10th symbol.

So far I have:

var street_1 = document.getElementById         


        
相关标签:
4条回答
  • 2020-12-22 03:57

    in html you can't define sub elements in the value of input fields because it is allways a simple string and not a html element. so you only can define the color for the input element and the complete text.

    <input type="text" value="my <em style='color: red;'>test</em>"> is not possible

    <input type="text" value="my test" style="color: red;"> is the only way to mark the text

    what can be a sollution, define a simple div tag, write the value of your input filed inside that, and mark the text in that div tag by surrounding with a span tag and setting a class to this

    Edit:

    best practice is, simply show a red border on the input field and tell the user with a popup what exactly is wrong with his input (bootstrap modals or jquery-confirm.js for excample)

    0 讨论(0)
  • 2020-12-22 03:58

    You can hide the input field, and add another span element that displays its value as follows:

    HTML:

    <div>
      <input type="text">
      <span class="text"></span>
    </div>
    

    CSS:

    input {
      opacity: 0;
      width: 100%;
    }
    
    div {
      position: relative;
      border: 1px solid #000;
    }
    
    .text {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
    }
    
    .red {
      color: red;
    }
    

    JS:

    var span = document.querySelector('span');
    var input = document.querySelector('input');
    
    input.addEventListener('keydown', function(evt) {
      var value = evt.target.value;
      span.innerHTML = value.substring(0, 10) + '<span class="red">' + value.substring(10) + '</span>'
    });
    

    You can find a working fiddle here https://jsfiddle.net/v127c14p/

    0 讨论(0)
  • 2020-12-22 04:05

    You can do a substring and append a element like span and then target the span with css or js directly.

    0 讨论(0)
  • 2020-12-22 04:11

    You can use CSS. Although javascript library need to load everytime

    you mean something like this

    <div>
    HELL<span class="red" style="color:red">O</span>
    </div>
    
    0 讨论(0)
提交回复
热议问题