小程序模板网

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

发布时间:2021-06-07 08:51 所属栏目:小程序开发教程

小程序对解析标签字符串不友好,有时候要处理一些搜索内容、关键字、段落中高亮展示检索到的匹配文字就会比较麻烦。

[HTML] 

<view class="section">
    <view class="view-search">
        <input class="view-search-input" value="{{keyName}}" placeholder="输入搜索关键词" 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": "是的,挺不错" },
    ], // 内容原始数组 (如果是后台请求的数据,就不需要两个数组了))
    searchDataList: [
      { "id": "1", "text": "挺不错的小老弟" },
      { "id": "2", "text": "是的,挺不错" },
    ], // 用来搜索的复制数组
  },

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

  // 搜索关键字
  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) { },
})


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/26102.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询