-->

How to change color for mismatch words in HTML usi

2020-08-05 11:09发布

问题:

I have a span and an input field; I want to change the color of the text in span when I enter that text in input field.

Following is my code:

i want, if i type wrong word then that word will red in 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();" />

回答1:

This code should highlight in green the parts that match, and in red the parts that do not.

It works by finding the index of the first occurrence of the text that the user entered, and adding the starting and ending <span> tags around it.

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()">



回答2:

This is A simple way to do to this task without using regexp. Now you can every time use only replaceColor function for any string object.

    String.prototype.replaceColor = function(search, replacement, replaceContainer) {
        var target = this;
        var toReplace = target.split(search).join(replacement);
        replaceContainer.html(toReplace);
    };

    $( document ).ready(function() {
        var container = $('#para');
        var str = container.text();


        $('#in').on('keyup', function() {
            var replacement = "<span class='redText'>" + this.value +"</span>";
            str.replaceColor(this.value, replacement, container);
        });
    });
    .redText {
        color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="para">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

<input type="text" id="in" value="" placeholder="input text"/>



回答3:

new RegExp()

The following example uses regular expressions created from the value of the <input> on input.

Regular expressions are patterns used to match character combinations in strings.

If the (case sensitive) value is matched by replace(), we capture the match, and wrap it in <span> tags, which have a CSS rule dictating that they should be color: red.
With the "g" (global) flag set, replace() acts on every matched string, instead of only the first if this flag is omitted.

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

We then set the innerHTML of the <p> to the textContent of the <p> with all the matched text wrapped in <span>s.

The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
...
This property provides a simple way to completely replace the contents of an element.


textContent returns the concatenation of the textContent property value of every child node, excluding comments and processing instruction nodes. This is an empty string if the node has no children.

Finally we use classList.toggle() with its optional second argument as the value of the <input>; if the <input> has a value, anything not typed correctly will be colored red, otherwise will remain the fallback text color.

When a second argument is present: If the second argument evaluates to true, add specified class value, and if it evaluates to false, remove it.

const para = document.querySelector( "p" );
document.querySelector( "input" ).addEventListener( "input", function() {
  const input = this.value,
        content = para.textContent;
  para.innerHTML = input ? content.replace(
      new RegExp( "(" + input + ")", "g" ), // search for "input.value"
      "<span>$1</span>" // replace with "<span>input.value</span>"
    ) : content;
  para.classList.toggle( "active", input );
}, false );
body {
  font-family: sans-serif;
  color: #444;
}
p.active {
  color: darkred;
}
span {
  color: darkgreen;
}
input {
  padding: .5em;
  vertical-align: .1em;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<label>Change the color of this text: <input type="text"></label>