关注前端开发
关注用户体验

页内搜索功能源代码

<!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>

赞(0)
未经允许不得转载:大前端 » 页内搜索功能源代码
分享到: 更多 (0)

评论 3

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #3

    I dont think Ive read anything like this before. So good to find somebody with some original thoughts on this subject. cheers for starting this up. This blog is something that is needed on the web, someone with a little originality. Good job for bringing something new to the internet!

    Paris Neddenriep2周前 (03-11)回复
  2. #2

    可以搜索但不跳,数据多了还是难找

    药代邦2年前 (2017-04-21)回复
  3. #1

    请问,这个功能怎么使用??

    重庆傅律师6年前 (2013-09-09)回复

themebetter 国内更好的WordPress主题服务商

立即前往