JavaScript:如何将颜色更改为输入字段中字符串的仅一部分? [英] JavaScript: How to change color to only part of the string in an input field?

查看:45
本文介绍了JavaScript:如何将颜色更改为输入字段中字符串的仅一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,我想让第10个符号后的字符变成红色.

到目前为止,我有:

  var street_1 = document.getElementById('street_1');street_1.style.color =红色"; 

更改所有字符的颜色.然后我尝试使用:

street_1.value.substring(10,100).style.color ="red";

自我所了解的 .style 以来,那当然是行不通的,它仅适用于整个字段,而不仅仅是值.

由于我对JS完全陌生,所以我真的不知道该如何处理.

解决方案

您可以隐藏输入字段,并添加另一个显示其值的 span 元素,如下所示:

HTML:

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

CSS:

 输入{不透明度:0;宽度:100%;}div {职位:相对边框:1px实线#000;}.文本 {位置:绝对;最高:0;左:0;宽度:100%;高度:100%;z索引:-1;}.红色的 {红色;} 

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>'}); 

您可以在此处 https://jsfiddle.net/v127c14p/

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('street_1');
street_1.style.color = "red";

Which changes the color of all the characters. Then I tried using:

street_1.value.substring(10,100).style.color = "red";

which of course didn't work since .style as I learned only works for the entire field and not just the value.

Since im completely new to JS I really have no idea how to approach this.

解决方案

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/

这篇关于JavaScript:如何将颜色更改为输入字段中字符串的仅一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆