Skip to content

Instantly share code, notes, and snippets.

@mcattx
Last active January 28, 2016 08:36
Show Gist options
  • Select an option

  • Save mcattx/31562356dfff160d12d0 to your computer and use it in GitHub Desktop.

Select an option

Save mcattx/31562356dfff160d12d0 to your computer and use it in GitHub Desktop.
页面关键字高亮
//关键字从页面的 url 获取;譬如: www.yourwebsite.com?p=1234
var keyword = window.location.search.substr(3);
keyword = decodeURIComponent(keyword);
/**
* 页面高亮关键字
* @param {string} targetNode: 要进行高亮的范围节点,需要类名(不需要加.)。
* @param {string} keyword: 高亮的关键字
* @param {array} exclude: 要排除的节点名字数组
*/
function HighLight(targetNode, keyword, excludeArr) {
this.targetNode = targetNode;
this.keyword = keyword;
this.excludeArr = excludeArr;
this._init();
};
HighLight.prototype = {
constructor: HighLight,
_init: function() {
this._addHightLightClass();
},
_getNode: function() {
var node = document.body;
var targetNode = this.targetNode;
var result = null;
for (var i = 0, j = node.childNodes.length; i < j; i++) {
if (node.childNodes[i].className === targetNode) {
result = node.childNodes[i];
break;
}
}
return result;
},
_addHightLightClass: function(node) {
if (!node) {
node = this._getNode();
}
var keyword = this.keyword;
var excludeArr = this.excludeArr;
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes[i];
var textValue = childNode.nodeValue;
if (excludeArr.indexOf(childNode.className) > -1) {
continue;
} else {
if (textValue && this._trim(textValue).length && textValue.indexOf(keyword) > -1) {
var re = new RegExp('(' + keyword + ')','g');
var newStr = '<span class="highlight">' + keyword +'</span>';
var newNodeValue = textValue.replace(re, newStr);
childNode.parentNode.innerHTML = newNodeValue;
} else {
this._addHightLightClass(childNode);
}
}
}
},
_trim: function(string, chars, guard) {
var reTrim = /^\s+|\s+$/g;
if (!string) {
return string;
}
if (guard || chars === undefined) {
return string.replace(reTrim, '');
}
chars = (chars + '');
if (!chars) {
return string;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment