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

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

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

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

  • wxml



  
    {{motto}}
  
  
    
      {{util.myReplace(item.text)}} 
      {{util.myReplace(item.text)}}
    
  

  • 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(" ", " ");
  if (content.indexOf(" ") != -1) {
    return myReplace(content);
  }

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

运行结果

image.png

源码地址

你可能感兴趣的:(微信小程序实现某个关键字高亮显示)