我有一个span
和input
字段;当我在输入字段中输入文本时,我想更改span
中文本的颜色。
以下是我的代码:
我想要,如果我输入了错误的单词,那么该单词的跨度将为红色
var i=0;
var idx=0;
document.body.onkeydown = function(e){
if(e.keyCode == 32 )
{
highlight();
}
}
function highlight() {
var str= document.getElementById("pera").innerText.split(' ');
var text= str[i];
var wrdl = text.length;
var inputText = document.getElementById("pera");
var innerHTML = inputText.innerText;
var pretext = innerHTML.slice(0, idx);
var postext = innerHTML.slice(idx+text.length);
if ( idx >= 0 && text!="")
{
var highlightedText = pretext;
highlightedText += "<span class='highlight'>";
highlightedText += text;
highlightedText += "</span>";
highlightedText += postext;
document.getElementById("pera").innerHTML=highlightedText;
}
i++;
idx += parseInt(text.length+1);
}
.highlight
{
background-color:yellow;
}
<span id="pera">This paragraph is a value of span</span>
</br>
<input type="text" id ="inp" onfocus="highlight();" />
最佳答案
此代码应以绿色突出显示匹配的部分,并以红色突出显示不匹配的部分。
它的工作原理是找到用户输入的文本的第一个匹配项的索引,并在其周围添加开始和结束<span>
标签。
function highlight() {
const text = "This paragraph is a value of span"; //The actual text to compair the value against
var value = document.getElementById("in").value; //The input value
var startingIndex = text.indexOf(value); //The string index where the value begins in the paragraph
if (startingIndex!=-1) { //If the value is within the text
var endingIndex = startingIndex+value.length; //The string index where the value ends is just the length of the value added to the starting index
var highlightedText = text.slice(0,startingIndex); //The text from the beginning to the start of the highlight
highlightedText += "<span style=\"color:green;\">"; //Add the HTML which will cause the highlight
highlightedText += text.slice(startingIndex,endingIndex); //Add the text to highlight
highlightedText += "</span>"; //Add the HTML which will cause the end of the highlight
highlightedText += text.slice(endingIndex); //Add the remaining text
document.getElementById("para").innerHTML = highlightedText; //Set the HTML of the paragraph to be the new, highlighted string that we made.
}
}
<span id="para" style="color:red"><span style="color:green">This paragraph is</span> a value of span</span><br><br>
<input type="text" id="in" value="This paragraph is" oninput="highlight()">