JavaScript:如何将颜色更改为输入字段中字符串的仅一部分? [英] JavaScript: How to change color to only part of the string in an input field?
问题描述
我有一个输入字段,我想让第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屋!