首页 > 其他 > 详细

页面的关键词高亮

时间:2018-02-27 12:28:49      阅读:221      评论:0      收藏:0      [点我收藏+]
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‘)

 

页面的关键词高亮

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!