//形参说明:
//searchBox: 搜索框的ID
//searchText:需要进行搜索的文本所在容器的ID
function search(searchBox,searchText){
s1=document.getElementById(searchBox).value;//搜索框中的文本内容
s2=document.getElementById(searchText).innerHTML;
var pos=s2.indexOf(s1);
if(pos==-1) alert('can not find');
else{
str="<font style='background-color:yellow'>"+s1+"</font>";
var startIndex=0;
var newText='';
do{
newText+=s2.substring(startIndex,pos)+str;
startIndex=pos+s1.length;
pos=s2.indexOf(s1,startIndex);
}while(pos!=-1)
newText+=s2.substring(startIndex);
document.getElementById(searchText).innerHTML=newText;
}
}
要点:
s1:原字符串;
str="<font style='background-color:yellow'>"+s1+"</font>";
str:将字符串s1的背景颜色变黄