<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>关键字高亮</title>
<link rel="stylesheet" type="text/css" href="reset.css">
<style type="text/css">
#demo .Highlight{
color: red;
}
#text .Highlight{
color: red;
}
</style>
</head>
<body>
<p id="demo">我是关键字的高亮显示文本,高亮的文字有JavaScript,还有CSS,以及HTML5!</p>
<p id="text">我是关键字的高亮显示文本,高亮的文字有JavaScript,还有CSS,以及HTML5!</p>
<script type="text/javascript">
var Highlight = {
arr : [],
init : function (ops){
this.arr[ops.id] = {
id : ops.id,
arr : ops.arr
}
this.show(this.arr[ops.id]);
},
show : function (obj){
obj.html = document.getElementById(obj.id).innerHTML;
for (var i = 0 ; i < obj.arr.length ; i ++) {
// 全局匹配 替换
var reg = new RegExp(obj.arr[i],'g');
obj.html = obj.html.replace(reg,"<span class='Highlight'>"+obj.arr[i]+"</span>");
}
document.getElementById(obj.id).innerHTML = obj.html;
}
}
window.onload = function (){
// 使用方法
// id 必须
// 默认为id 高亮内容添加class为 Highlight span 标签包裹,直接在style中写样式即可
Highlight.init({id:"demo",arr:["JavaScript","CSS","HTML5"]});
Highlight.init({id:"text",arr:["文本","高亮"]});
}
</script>
</body>
</html>
网友评论