欢迎光临,了解微信小程序开发,就上易用通! QQ登录

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

发布:2021-06-07 08:50浏览:来源:网络 编辑:admin

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

[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) { },
})




免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。