[英]Javascript - Change certain character color in input
var input = document.getElementById("wordTyped"); var word = document.getElementById("wordGenerated").innerHTML; window.onload = function() { window.onkeydown = submit; function submit(evt) { if (evt.key == "Enter" && input.value == word) { input.value = ""; input.style.color = "black"; } else if (evt.key == "Enter" && input.value != word) { for (i = 0; i < word.length; i++) { // Below is what I'm querying about if (input.value[i] != word[i]) { input.style.color = "red"; } } } } }
<div id="wordGenerated">illustration</div> <input id="wordTyped" type="text" />
我想我问的甚至都不可能,但我想尝试更改与word
不匹配的input
字符的颜色
例如,
wordGenerated:插图
wordTyped:iilustration
然后,在Enter
,wordTyped中的第二个“ i”应将其颜色更改为红色
我尝试做input.value.style.color[i] = "red"
和input.value[i].style.color = "red"
,但是这些返回的TypeError颜色为undefined。
上面的代码将整个输入文本的颜色更改为红色。
您只需要将字母包装在span元素中即可。 注意:下面的代码只是概念的证明,我没有对其进行优化。 我把优化部分留给了你。 祝好运。
var input = document.getElementById("wordTyped"); var word = document.getElementById("wordGenerated").innerHTML; window.onload = function() { window.onkeydown = submit; function submit(evt) { var newWord=document.getElementById("wordGenerated"); newWord.innerHTML=""; if (evt.key == "Enter" && input.value == word) { input.value = ""; input.style.color = "black"; } else if (evt.key == "Enter" && input.value != word) { for (i = 0; i < input.value.length; i++) { // Below is what I'm querying about if (input.value[i] != word[i]) { var child = document.createElement( "span" ); child.className='colored'; child.innerHTML = input.value[i]; newWord.appendChild( child ); } else { var child = document.createElement( "span" ); child.innerHTML = input.value[i]; newWord.appendChild( child ); } } } } }
.colored { color: red; }
<div id="wordGenerated">illustration</div> <input id="wordTyped" type="text" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.