Code:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=gb2312" /> <title>Text highlighting</title> <style>. bg-red{Background-color:Red; } </style></Head><Body> <Divstyle= "margin:20px auto;text-align:center;"> <inputtype= "text"ID= "Search"placeholder= "Enter what you want to search for"> </Div> <Divstyle= "width:90%;margin:20px auto;"ID= "Con"> <P>In web development often encounter the need to dynamically listen to the changes in input box values, if you use OnKeyDown, onkeypress, onkeyup this several keyboard events to monitor, can not listen to the right-click Copy, clip and paste these operations, processing combination shortcut keys is also very troublesome.</P> <P>JS Replace the default substitution replaces only the first matching character, if the string has more than two characters can not be replaced, it is necessary to do a little operation, to replace all. var StrM = "This is the string to be replaced AH Ah!" ...</P> <P>Recently in the company to help a child to see a very strange bug, is a small MFC GUI, in the customer environment, an input box data is always garbled, resulting in data from the database can not be found. But the strange thing is that we can't reproduce it in our environment because our test environment uses win ...</P> </Div></Body><Script>window.onload= function () { varPnodes=document.getElementById ('Con'). getElementsByTagName ('P'); varSearchnode=document.getElementById ('Search'); varPtextarr= []; for(varI=0; I<pnodes.length; I++) {Ptextarr.push (pnodes[i].innerhtml); } //listen for changes to the contents of the text boxSearchnode.addeventlistener ('input', function(e) {vartext= This. Value; for(varI=0; I<pnodes.length; I++){ varPnode=Pnodes[i]; //paragraph Nodes varPtext=Ptextarr[i]; //the text of each paragraph varValues=ptext.split (text); varPnodetext=Values.join ('<span class= "bg-red" >'+text+'</span>'); Pnode.innerhtml=Pnodetext; } }) }</Script></HTML>
Effect:
JavaScript for paragraph text highlighting