正文内容js高亮效果
//高亮显示搜索到的关键字
function HeightLight(Keyword)
{
//文本选择器
var TextRange;
//是否找到
var Found=false;
//找到的次数
var Count = 0;
TextRange = document.body.createTextRange();
Found = TextRange.findText(Keyword);
if (Found)
{
Count++;
}
while (Found && Count > 0)
{
TextRange.pasteHTML('<span style="background:yellow">' + Keyword + '</span>');
//将滚动条定位到第一次查到的视口范围内
if(Count==1)
{
TextRange.scrollIntoView();
}
//继续查找
Found = TextRange.findText(Keyword);
if (!Found)
{
Count = 0;
}
else
{
Count++;
}
}
}
正则式法
function highLight(ele,keys)
{
var reg = new RegExp("(" + keys.replace(/,/,"|") + ")","g");
ele.innerHTML = ele.innerHTML.replace(reg,"<font color=\"red\">$1</font>");
}