微信小程序实现某个关键字高亮显示

微信小程序实现某个关键字高亮显示

需求: 实现对列表搜索的关键字进行高亮显示

  • js
Page({
  data: {
    motto: '<高亮 A>',
    list:[
      'WaC38',
      'W2A81',
      'E2A18',
      'E2A61',
      'E3Ca1',
      'E2C81',
      'E4a43',
      'E4A65'
    ]
  },
  onLoad: function () {
  }
})

  • wxml
<!--公共的wxs工具-->
<wxs src="../../wxs/highLight.wxs" module="util" />
<view class="container">
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
  <view wx:for="{{list}}" wx:key="item" >
    <view wx:for="{{util.highLight(item,'A')}}" wx:key="item" style="float:left;">
      <text wx:if="{{item.type==1}}" decode="true" space="true" style='color:red;'>{{util.myReplace(item.text)}} </text>
      <text wx:else decode="true" space="true">{{util.myReplace(item.text)}}</text>
    </view>
  </view>
</view>
  • wxs ---公共的处理高亮的方法
var sliceStr = function (str, len) {
  var len = len || 8;
  if (str != null) {
    if (str.length > len) {
      return str.substring(0, len) + "...";
    } else {
      return str;
    }
  }
  return '';
}
var highLight = function (content, key, res) {
  if (res == undefined) {
    res = [];
  }
  key = key.toUpperCase();
  var keyLen = key.length;
  var tmp = content.toUpperCase();
  if (tmp.length >= keyLen && keyLen > 0) {

    var index = -1;
    index = tmp.indexOf(key);

    if (index != -1) {
      var n = content.substring(0, index);
      res.push({
        type: 2,
        text: n
      });
      var y = content.substring(index, index + keyLen);
      res.push({
        type: 1,
        text: y
      });
      content = content.substring(index + keyLen, content.length);
      highLight(content, key, res);
    } else {
      res.push({
        type: 2,
        text: content
      });
    }
  } else {
    res.push({
      type: 2,
      text: content
    });
  }
  return res;
}
var myReplace = function (content) {
  content = content.replace(" ", "&nbsp;");
  if (content.indexOf(" ") != -1) {
    return myReplace(content);
  }

  return content;
}
module.exports.myReplace = myReplace;
module.exports.highLight = highLight;
module.exports.sliceStr = sliceStr;

运行结果

image.png

源码地址

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 因新工作主要负责微信小程序这一块,最近的重心就移到这一块,该博客是对微信小程序整体的整理归纳以及标明一些细节点,初...
    majun00阅读 12,166评论 0 9
  • ******************逻辑层****************** 1:app.json文件用来对微信...
    名字_都被占了阅读 4,990评论 0 2
  • 简介 微信小程序入门门槛低、开发周期短、代码编写灵活、传播速度快等优点让微信小程序迅速火爆,开发者纷纷涌入,任何语...
    大公爵阅读 9,872评论 0 10
  • 《财商》原来是一本小说,一开始复杂的外国人名,很难快速进入故事。不过,情节展开很快。老董事长宣布重病引退,海沃德(...
    雨橙suri阅读 3,446评论 0 27
  • 柳校在亲子读写群里给大家推荐了一篇文章《中国的教育问题要想从根本性改变,必须从这件事入手》,“这件事“...
    小兔麻麻_ace0阅读 2,271评论 0 0

友情链接更多精彩内容