1 /**
2 * Created by dell on 2018/2/28.
3 */
4 (function ($) {
5 $.fn.GL = function (options) {
6 var dataop = {
7 ocolor:'red',
8 oshuru:'高亮',
9 };
10 var chuancan = $.extend(dataop,options);
11 $(this).each(function()//先遍历,清除上一次的样式
12 {
13 var _this = $(this)
14 _this.find($(".glnow")).each(function()//找到所有highlight属性的元素;
15 {
16 $(this).css({color:""});//将他们的属性去掉;
17 });
18 });
19 if(chuancan.oshuru==''){
20 return false;
21 }else{
22 var regExp = new RegExp("(" + chuancan.oshuru.replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");//创建正则表达式,g表示全局的,如果不用g,则查找到第一个就不会继续向下查找了;
23 $(this).each(function()//遍历文章;
24 {
25 var _this1 = $(this)
26 var html = _this1.html();
27 var newHtml = html.replace(regExp, '<span class="glnow" style="color:'+chuancan.ocolor+'">'+chuancan.oshuru+'</span>');//将找到的关键字替换,加上highlight属性;
28 _this1.html(newHtml);//更新文章;
29 });
30 }
31 }
32 })(jQuery);
1 $(".one").click(function () {
2 var otext = $("input").val();
3
4 $('.text').GL({
5 ocolor:'red', //设置关键词高亮颜色
6 oshuru:otext //设置要显示的关键词
7 });
8 })
<p class="text">我是测试文字,测试<span class="glnow" style="color:red">高亮</span>功能</p>
<p class="text">我是测试文字,测试<span class="glnow" style="color:red">高亮</span>功能</p>
<p class="text">我是测试文字,测试<span class="glnow" style="color:red">高亮</span>功能</p>
<p class="text">我是测试文字,测试<span class="glnow" style="color:red">高亮</span>功能</p>