关注前端开发
HTML5、CSS3、Javascript

页内搜索功能源代码

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd”>

<html http://www.w3.org/1999/xhtml”>http://www.w3.org/1999/xhtml”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />

<META name=”Author” content=”Sheneyan” />

<script type=”text/javascript”>

function encode(s){

return s.replace(/&/g,”&”).replace(/</g,”<“).replace(/>/g,”>”).replace(/([\\\.\*\[\]\(\)\$\^])/g,”[url=file://\\$1]\\$1[/url]”);

}

function decode(s){

return s.replace(/\\([\\\.\*\[\]\(\)\$\^])/g,”$1″).replace(/>/g,”>”).replace(/</g,”<“).replace(/&/g,”&”);

}

function highlight(s){

if (s.length==0){

alert(‘ 搜索关键词未填写!’);

return false;

}

s=encode(s);

var obj=document.getElementsByTagName(“body”)[0];

var t=obj.innerHTML.replace(/<span\s+class=.?highlight.?>([^<>]*)<\/span>/gi,”$1″);

obj.innerHTML=t;

var cnt=loopSearch(s,obj);

t=obj.innerHTML

var r=/{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g

t=t.replace(r,”<span class=’highlight’>$1</span>”);

obj.innerHTML=t;

alert(” 搜索到关键词”+cnt+”处”)

}

function loopSearch(s,obj){

var cnt=0;

if (obj.nodeType==3){

cnt=replace(s,obj);

return cnt;

}

for (var i=0,c;c=obj.childNodes;i++){

if (!c.className||c.className!=”highlight”)

cnt+=loopSearch(s,c);

}

return cnt;

}

function replace(s,dest){

var r=new RegExp(s,”g”);

var tm=null;

var t=dest.nodeValue;

var cnt=0;

if (tm=t.match(r)){

cnt=tm.length;

t=t.replace(r,”{searchHL}”+decode(s)+”{/searchHL}”)

dest.nodeValue=t;

}

return cnt;

}

</script>

<style type=”text/css”>

.highlight{background:green;font-weight:bold;color:white;}

</style>

</head>

<body>

转载请注明出处大前端 » 页内搜索功能源代码

分享: