javascript网页关键字高亮代码
作者:
非常不错的关键字高亮代码,用js实现,这个方法不错
//高亮网页关键字的javascript代码
var keys = [
["脚本",https://www.jb51.net,"#ff0000"],
["小说",http://www.kanshule.com,"#00ff00"],
["念经","http://www.baidu.com","#0000ff"],
["工会","http://www.baidu.com","#cc6600"]
]
var bookmark;
if(document.createRange){
var range = document.createRange();
}else{
var range = document.body.createTextRange();
bookmark = range.getBookmark();
}
var key;
for(var i = 0;key = keys[i];i++){
if(range.findText){
range.collapse(true);
range.moveToBookmark(bookmark);
while(range.findText(key[0])){
range.pasteHTML(range.text.fontcolor(key[2]));
}
}else{
var s,n;
s = window.getSelection();
s.collapse(document.body,0);
while(window.find(key[0])){
var n = document.createElement("SPAN");
n.style.color=key[2];
s.getRangeAt(0).surroundContents(n);
}
}
}
var keys = [
["脚本",https://www.jb51.net,"#ff0000"],
["小说",http://www.kanshule.com,"#00ff00"],
["念经","http://www.baidu.com","#0000ff"],
["工会","http://www.baidu.com","#cc6600"]
]
var bookmark;
if(document.createRange){
var range = document.createRange();
}else{
var range = document.body.createTextRange();
bookmark = range.getBookmark();
}
var key;
for(var i = 0;key = keys[i];i++){
if(range.findText){
range.collapse(true);
range.moveToBookmark(bookmark);
while(range.findText(key[0])){
range.pasteHTML(range.text.fontcolor(key[2]));
}
}else{
var s,n;
s = window.getSelection();
s.collapse(document.body,0);
while(window.find(key[0])){
var n = document.createElement("SPAN");
n.style.color=key[2];
s.getRangeAt(0).surroundContents(n);
}
}
}