码迷,mamicode.com
首页 > 其他好文 > 详细

页面的关键词高亮

时间:2018-02-27 12:43:30      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:post   标签   get   AC   replace   odi   result   替换   return   

function keyLight(id, key, bgColor) {
  var oDiv = document.getElementById(id),
  sText = oDiv.innerHTML,
  bgColor = bgColor || "orange",
  sKey = "<span style=‘color: " + bgColor + ";‘>" + key + "</span>",
  num = -1,
  rStr = new RegExp(key, "g"),
  rHtml = new RegExp("\<.*?\>", "ig"), //匹配html元素
  aHtml = sText.match(rHtml); //存放html元素的数组
  sText = sText.replace(rHtml, ‘{~}‘);  //替换html标签
  sText = sText.replace(rStr, sKey); //替换key
  sText = sText.replace(/{~}/g, function () {  //恢复html标签
  num++;
  return aHtml[num];
  });
  oDiv.innerHTML = sText;
}
var key1 = keyLight(‘result‘, ‘关键词‘);
var key2 = keyLight(‘result‘, ‘关键词‘, ‘red‘)

 

页面的关键词高亮

标签:post   标签   get   AC   replace   odi   result   替换   return   

原文地址:https://www.cnblogs.com/caichunbao/p/8478175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!