微信小程序?qū)崿F(xiàn)某個關(guān)鍵字高亮顯示

微信小程序?qū)崿F(xiàn)某個關(guān)鍵字高亮顯示

需求: 實(shí)現(xiàn)對列表搜索的關(guān)鍵字進(jìn)行高亮顯示

  • 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;

運(yùn)行結(jié)果

image.png

源碼地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 因新工作主要負(fù)責(zé)微信小程序這一塊,最近的重心就移到這一塊,該博客是對微信小程序整體的整理歸納以及標(biāo)明一些細(xì)節(jié)點(diǎn),初...
    majun00閱讀 7,633評論 0 9
  • ******************邏輯層****************** 1:app.json文件用來對微信...
    名字_都被占了閱讀 1,320評論 0 2
  • 簡介 微信小程序入門門檻低、開發(fā)周期短、代碼編寫靈活、傳播速度快等優(yōu)點(diǎn)讓微信小程序迅速火爆,開發(fā)者紛紛涌入,任何語...
    大公爵閱讀 4,503評論 0 10
  • 《財(cái)商》原來是一本小說,一開始復(fù)雜的外國人名,很難快速進(jìn)入故事。不過,情節(jié)展開很快。老董事長宣布重病引退,海沃德(...
    雨橙suri閱讀 569評論 0 27
  • 柳校在親子讀寫群里給大家推薦了一篇文章《中國的教育問題要想從根本性改變,必須從這件事入手》,“這件事“...
    小兔麻麻_ace0閱讀 341評論 0 0

友情鏈接更多精彩內(nèi)容