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

2019-06-18  本文已影响0人  趙小傑

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

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

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

<!--公共的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>
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

源码地址

上一篇下一篇

猜你喜欢

热点阅读