• Angularjs 搜索关键字高亮显示


    需求分析:
      根据关键字搜索网页内容,并且高亮显示内容中的关键字
    细节分析:
      1、每次执行搜索操作,需清空上一次结果
      2、需区分html标签和正常文本内容,否则为关键字添加样式以后会出现标签内容被显示的情况
    代码思路:
      利用正则表达式匹配关键字
        使用javascript字符串替换的方式,将关键字替换成<span class='red'>关键字</span>
      为了避免出现
        当关键字为 'p' 时候,将标签<p>替换成<<span>p</span>>……等等
      的情况
      所有匹配和替换操作只针对当前DOM元素中文本节点,通过递归函数遍历操作所有节点
    前端框架:

    angularjs^1.2.9

     1      $scope.myData = '<div>woshihight<h2>womei<b>bbb</b>shihigh<span>haha</span></h2><span>1000pxhight</span><ul><li>1high</li><li>2hight span light hight< p></li></ul><a href="index.html">这个是链接地址hight</a></div>';
     2       $scope.myDataCp = angular.copy($scope.myData);
     3       $scope.key = '';
     4       $scope.searchKey = function() {
     5         if($scope.key != '') {
     6           searchHighLight($scope.key);
     7         }
     8       }
     9 
    10       function searchHighLight(key) {
    11         var _element = angular.element($scope.myDataCp);
    12         nodeRecursion(_element[0],key);
    13         var _htmlStr = _element[0].innerHTML.toString();
    14         _htmlStr = _htmlStr.replace(/_1000px_/g, '<span class="red">').replace(/_xp0001_/g, '</span>');
    15         $scope.myData = _htmlStr;
    16       }
    17 
    18       //循环遍历替换所有文本节点内容
    19       function nodeRecursion(e, key) {
    20         var reg = new RegExp(key, 'g');
    21         var _count = e.childNodes.length;
    22         for(var _i=0; _i < _count; _i++) {
    23           if(e.childNodes.item(_i).nodeType == 3) {
    24             var _str = e.childNodes.item(_i).data;
    25 
    26             if(_str.indexOf(key)!=-1) {
    27               _str = _str.replace(reg,'_1000px_'+key+'_xp0001_');
    28             }
    29             e.childNodes.item(_i).data = _str;
    30           } else {
    31             nodeRecursion(e.childNodes.item(_i), key);
    32           }
    33         }
    34       }    

    其他说明:

    searchKey //点击搜索按钮调用该方法

    $scope.myData 中的html字符串必须有一个根节点,比如这里的div

    html页面中加载该html字段需要ng-bind-html指令,该指令需要加载ngSanitize模块

  • 相关阅读:
    OC2_数组操作
    OC1_数组创建
    OC6_字符串练习
    Python3学习笔记12-定义函数及调用
    Python3学习笔记11-循环语句
    Python3学习笔记10-条件控制
    Python3学习笔记09-字典
    Python3学习笔记08-tuple
    Python3学习笔记07-List
    Python3学习笔记05-数字
  • 原文地址:https://www.cnblogs.com/1000px/p/6293539.html
Copyright © 2020-2023  润新知