类似百度搜索关键字,并高亮显示

1、类似百度搜索关键字,并高亮显示关键字内容

1.1 关键字高亮函数设置

heghlight() {
            this.searchKeyInfo();
           //   页面中需要高亮的容器
            let searchArea = [$('.infoTitle'),$('.infoTag'),$('.schInfoBody'),$('.schInfoFoot')]       
            this.clearSelection(searchArea);     //先清空一下上次高亮显示的内容;
            var searchText = this.search ;    //获取你输入的关键字;
            if (searchText.length > 0) {
               //  创建正则表达式,g表示全局的,如果不用g,则查找到第一个就不会继续向下查找了;
                var regExp = new RegExp(searchText, 'g'); 
                $('.infoTitle').each(function (){   //遍历要查询的区域;
                    var html = $(this).html();
              //   将找到的关键字替换,加上highlight属性;
                    var newHtml = html.replace(regExp, "<span class='highlight'>" + searchText + '</span>'); 
                    $(this).html(newHtml); //更新文章;
                });
            }
        },

1.2 清除选中的关键字高亮

clearSelection(arr) {
    $('.infoTitle').each(function (){//遍历
        $(this).find('.highlight').each(function (){       //找到所有highlight属性的元素;
            var thishtml = $(this).html();
            $(this)[0].outerHTML = thishtml;
            // $(this).replaceWith(thishtml); //将他们的属性去掉;
        });
    });
}
                

1.3 样式处理

.highlight{
    color: #D0021B;
}

1.4 高亮效果图

13100152-b9980df508a3949a.png
搜索关键字高亮.png

猜你喜欢

转载自blog.csdn.net/weixin_34357267/article/details/87228948