Principle:
Get the page source (document.referrer) when the page is loaded, analyze the search engine keyword, then get all the elements on the page, recursive query contains search keywords, if so, create a SPAN element, and apply the keyword style to replace the original node
The code is as follows |
Copy Code |
<script type= "Text/javascript" > <!-- Description: Get search engine keywords and highlight Finishing: Http://www.111cn.net
function Highlightword (Node,word) { Iterate into this nodes childnodes if (node.haschildnodes) { var hi_cn; for (hi_cn=0;hi_cn<node.childnodes.length;hi_cn++) { Highlightword (Node.childnodes[hi_cn],word); } }
And do this node itself if (Node.nodetype = = 3) {//Text node Tempnodeval = Node.nodeValue.toLowerCase (); Tempwordval = Word.tolowercase (); if (Tempnodeval.indexof (tempwordval)!=-1) { PN = Node.parentnode; if (pn.classname!= "Searchword") { Word has not already been highlighted! NV = Node.nodevalue; NI = Tempnodeval.indexof (tempwordval); Create a load of replacement nodes Before = document.createTextNode (Nv.substr (0,ni)); Docwordval = Nv.substr (ni,word.length); after = document.createTextNode (Nv.substr (ni+word.length)); Hiwordtext = document.createTextNode (docwordval); HiWord = document.createelement ("span"); Hiword.classname = "Searchword"; Hiword.appendchild (Hiwordtext); Pn.insertbefore (Before,node); Pn.insertbefore (Hiword,node); Pn.insertbefore (After,node); Pn.removechild (node); } } } }
function Googlesearchhighlight () { if (!document.createelement) return; ref = Document.referrer; if (Ref.indexof ('? ') = = 1) return; QS = ref.substr (Ref.indexof ('? ') +1); QSA = Qs.split (' & '); for (i=0;i<qsa.length;i++) { Qsip = qsa[i].split (' = '); if (qsip.length = = 1) continue; if (qsip[0] = = ' Q ' | | qsip[0] = = ' P ') {//q= for Google, p= for Yahoo Words = Unescape (decodeURIComponent (Qsip[1].replace (/+/g, ')). Split (/s+/); for (w=0;w<words.length;w++) { Highlightword (document.getElementsByTagName ("body") [0],words[w]); } } } }
Window.onload = Googlesearchhighlight;
--> </script> |
CSS Code
The code is as follows |
Copy Code |
<style type= "Text/css" > . Searchword { Background-color:yellow; } </style> |