小程序模板網(wǎng)

小程序中搜索文字高亮顯示

發(fā)布時(shí)間:2021-06-07 08:51 所屬欄目:小程序開發(fā)教程

小程序?qū)馕鰳?biāo)簽字符串不友好,有時(shí)候要處理一些搜索內(nèi)容、關(guān)鍵字、段落中高亮展示檢索到的匹配文字就會比較麻煩。

[HTML] 

<view class="section">
    <view class="view-search">
        <input class="view-search-input" value="{{keyName}}" placeholder="輸入搜索關(guān)鍵詞" bindinput="bindInput" maxlength="11" />
    </view>
    <scroll-view class="scrollView" scroll-y>
        <view wx:for="{{searchDataList}}" wx:key="*this">
            <view class='oneText'>
                <text wx:for="{{item.text}}" wx:key="{{index}}" class="{{item == keyName ? 'searchHigh' : '' }}">{{item}}</text>
            </view>
        </view>
    </scroll-view>
</view>

 

[CSS] 

.view-search {
  padding: 12rpx 30rpx;
  box-sizing: border-box;
  position: relative;
}
.view-search-input {
  height: 70rpx;
  line-height: 70rpx;
  border: 2rpx solid #ccc;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 0px 70rpx 0px 20rpx;
  font-size: 32rpx;
}
 
.searchHigh {
  color: #409eff;
}
 
.scrollView {
    height: 80vh;
    background-color: #F5F5F5;
    box-sizing: border-box;
}
.oneText {
    line-height: 50rpx;
    margin: 30rpx;
    text-align: center;
    color: #9B9B9B;
    font-size: 32rpx;
}
.currentText {
    color: #0099FF;
}

 

[JavaScript]

const app = getApp();
const getInf = (str, key) => str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');

Page({
  data: {
    keyName: null,
    primaryListData: [
      { "id": "1", "text": "挺不錯的小老弟" },
      { "id": "2", "text": "是的,挺不錯" },
    ], // 內(nèi)容原始數(shù)組 (如果是后臺請求的數(shù)據(jù),就不需要兩個數(shù)組了))
    searchDataList: [
      { "id": "1", "text": "挺不錯的小老弟" },
      { "id": "2", "text": "是的,挺不錯" },
    ], // 用來搜索的復(fù)制數(shù)組
  },

  // 輸入框正在輸入
  bindInput: function (e) {
    var that = this;
    that.setData({
      keyName: that.trim(e.detail.value)
    })
    that.searchTap();
  },

  // 搜索關(guān)鍵字
  searchTap: function () {
    var that = this;
    var data = that.data.primaryListData;
    var newData = that.data.searchDataList;
    for (var i = 0; i < data.length; i++) {
      var dic = data[i];
      var newDic = newData[i];
      var text = dic["text"];
      newDic["text"] = getInf(text, that.data.keyName);
    }
    that.setData({
      searchDataList: newData,
    })
  },
  // 去除首尾的空格
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },

  onLoad: function (e) { },
})


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://u-renovate.com/wxmini/doc/course/26102.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢