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

后端 未结 4 695
一个人的身影
一个人的身影 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:58

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

    HTML:

    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) + '' + value.substring(10) + ''
    });
    

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

提交回复
热议问题