核心代码参见: http://www.kryogenix.org/code/browser/searchhi/
添加了对baidu的支持,解决了中文乱码不能高亮显示(这里vbs与js混在一起有些不爽,不知道有没有纯js的UrlDecode?)。
功能演示:在baidu(google还未收录本站)中搜索“ajax with asp 土哥”(即 http://www.baidu.com/s?wd=ajax+with+asp+%CD%C1%B8%E7&cl=3),然后点击搜索到的任一链接,在本站页面上的“ajax with asp 土哥”将高亮显示。
Function UrlDecode(enStr)
dim deStr
dim c,i,v
deStr=""
for i=1 to len(enStr)
c=Mid(enStr,i,1)
if c="%" then
v=eval("&h"+Mid(enStr,i+1,2))
if v<128 then
deStr=deStr&chr(v)
i=i+2
else
if isvalidhex(mid(enstr,i,3)) then
if isvalidhex(mid(enstr,i+3,3)) then
v=eval("&h"+Mid(enStr,i+1,2)+Mid(enStr,i+4,2))
deStr=deStr&chr(v)
i=i+5
else
v=eval("&h"+Mid(enStr,i+1,2)+cstr(hex(asc(Mid(enStr,i+3,1)))))
deStr=deStr&chr(v)
i=i+3
end if
else
destr=destr&c
end if
end if
else
if c="+" then
deStr=deStr&" "
else
deStr=deStr&c
end if
end if
next
URLDecode=deStr
end function
function isvalidhex(str)
isvalidhex= true
str=ucase(str)
if len(str)<>3 then isvalidhex= false:exit function
if left(str,1)<>"%" then isvalidhex= false:exit function
c=mid(str,2,1)
if not (((c>="0") and (c<="9")) or ((c>="A") and (c<="Z"))) then isvalidhex= false:exit function
c=mid(str,3,1)
if not (((c>="0") and (c<="9")) or ((c>="A") and (c<="Z"))) then isvalidhex= false:exit function
end function
</script>
<script language=javascript>
function highlightWord(node,word) {
// Iterate into this nodes childNodes
if (node.hasChildNodes) {
var hi_cn;
for (hi_cn=0;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 SearchHighlight() {
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 qsip = qsa[i].split(’=’);
if (qsip.length == 1) continue;
if (qsip[0] == ’q’ || qsip[0] == ’p’ || qsip[0] == ’wd’ ) { //搜索引擎关键字参数
words = UrlDecode(qsip[1].replace(//+/g,’ ’)).split(//s+/);
for (w=0;w highlightWord(document.getElementsByTagName("body")[0],words[w]);
}
}
}
}
window.onload = SearchHighlight;
</script>