首页 > 技术文章 > 微信小程序搜索并高亮关键字

xiaoyantongxue 2021-12-19 20:02 原文

更多解读可使用博客:

https://www.jianshu.com/p/86d73745e01c

 

实现流程:
1.在文本框中输入关键字key,如“比赛”,检索出比赛相关的列表
key = 小程序
2.处理结果列表:在key的前后加分隔符,如“%%”
3.通过第2步的分隔符进行切割,获取新的数组:str.split("%%")
4.页面for循环上面的新数组:与key相等,则高亮显示,否则常规样式显示
wxml:

<!-- 搜索并高亮关键字 -->
<view class="main">
    <view class="header-search">
        <image class="searchImg" src="/images/search_icon.png" mode="aspectFill" ></image>
        <input type="text" class="searchInput" focus="{{autoFocus}}" hold-keyborad="true" placeholder="请输入名称进行搜索" placeholder-style="color:#999999" bindinput = "input"></input>
        <view class="clearInput" bindtap = "clearInput" wx:if="{{searchText}}">
            <image class="clearInputImg" src="/images/clear.png" mode="aspectFill" ></image>
        </view>
    </view>
    <view style="padding: 0 24rpx;">
        <view class="searchResult" wx:if="{{searchText}}">
             <view class="searchText" data-type="1" bindtap = "toHandleSearch">搜索"{{searchText}}"</view>
             <view class="border-LR"></view>
        </view>
        <view wx:for="{{searchResultList}}" wx:key="index">
            <view class="searchResultItem" data-type="2" bindtap = "toHandleSearch">
                <image class="searchImg2" src="/images/search_icon.png" mode="aspectFill" ></image>
                <view class="searchResultItem-context">
                    <text wx:for="{{item.searchArray}}" wx:for-item="item2"  wx:key="index2" style="{{item2 == searchText?'color:#4E70C7':''}}">{{item2}}</text>
                </view>
            </view>
            <view class="border-item-LR"></view>
        </view>
    </view>
</view>

wxss

/* pages/gologin/gologin.wxss */
/* pages/search-effects/search-effects.wxss */
.header-search{
    position: relative;
    margin: 10rpx 24rpx 40rpx 24rpx;
}
/*搜索图标*/
.searchImg{
    position: absolute;
    left: 24rpx;
    bottom: 18rpx;
    width: 28rpx;
    height: 28rpx;
}
/*搜索图标*/
.searchImg2{
    width: 28rpx;
    height: 28rpx;
}
/*搜索文本框*/
.searchInput{
    width: 83%;
    height: 64rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-style: normal;
    font-weight: normal;
    line-height: 64rpx;
    color: #000000;
    opacity: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    min-height: unset;
    background: #f9f9f9;
    border-radius: 200rpx;
    padding: 0 58rpx;
}
/*清空文本框view*/
.clearInput{
    width: 100rpx;
    height: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 0;
    bottom: 0;
    z-index: 10;
}
/*清空图标*/
.clearInputImg{
    width: 36rpx;
    height: 36rpx;
    flex-shrink: 0;
}

/*搜索结果*/
.searchResult .searchText{
    max-width: 93%;
    font-family: PingFang SC;
    font-style: normal;
    font-weight: normal;
    font-size: 26rpx;
    line-height: 26rpx;
    color: #4e70c7;
    overflow-x: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding-bottom: 40rpx;
}
.searchResultItem {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
  }
.searchResultItem-context{
    font-family: PingFang SC;
    font-style: normal;
    font-weight: normal;
    font-size: 26rpx;
    line-height: 26rpx;
    color: #000000;
    margin-left: 20rpx;
    padding: 24rpx 0;
    overflow-x: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

wxjs

// pages/search-effects/search-effects.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchText:'',//文本框内容
        searchResultList:[],//搜索结果
        autoFocus: true,//自动聚焦
        holdKeyboard: true//focus时,点击页面的时候收齐键盘 true:不收起
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    //文本框输入
    input(e){
    //   console.log(e)
      this.setData({
        searchText:e.detail.value.trim()
      })
      //根据名称进行搜索
      this.getSearchListByName()
    },
    //根据名称进行搜索
    getSearchListByName(){
        let that = this
        //模拟数据请求
        var dataList=[
            {M_NAME:'小程序教程'},
            {M_NAME:'2020小程序大全'},
            {M_NAME:'微信小程序开源框架'},
            {M_NAME:'微信小程序组件化解决方法'},
            {M_NAME:'微信小程序API'},
            {M_NAME:'丰富的微信小程序组件'},
            {M_NAME:'第三方微信小程序组件'},
            {M_NAME:'自定义小程序UI组件'},
            {M_NAME:'小程序可滑动标签的使用'}
        ]
        var searchResultList = []
        for(var i=0;i<dataList.length;i++){
            let obj={
                M_NAME:dataList[i].M_NAME
            };
            //高亮字符串数组
            obj.searchArray=that.getHilightStrArray(dataList[i].M_NAME,this.data.searchText)
            searchResultList.push(obj)
        } 
        that.setData({
            searchResultList:searchResultList
        })
        // wx.request({
        //     url: 'http://192.168.0.76:8080/open/getSearchListByName', // 仅为示例,并非真实的接口地址
        //     data: {
        //         m_name:this.data.searchText
        //     },
        //     method: 'post',
        //     header: {
        //         'content-type': 'application/json' // 默认值
        //     },
        //     success(res) {
        //         console.log(res)
        //         var searchText = that.data.searchText
        //         if (res.data.errcode === 200) {
        //             var searchResultList = []
        //             //比赛 数据
        //             if(res.data.matchList){
        //                 for(var i=0;i<res.data.matchList.rows.length;i++){
        //                     let obj={
        //                         M_NAME:res.data.matchList.rows[i].M_NAME
        //                     };
        //                     //高亮字符串数组
        //                     obj.searchArray=that.getHilightStrArray(res.data.matchList.rows[i].M_NAME,searchText)
        //                     searchResultList.push(obj)
        //                 } 
        //             }
        //             that.setData({
        //                searchResultList:searchResultList
        //             })
        //         }
        //     },
        //     fail() {
        //     }
        // })
    },
    // 返回一个使用key切割str后的数组,key仍在数组中
    getHilightStrArray(str,key){
        return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
})

注意:下面的函数 比较关键

//返回一个使用key切割str后的数组,key仍在数组中
//str:字符串  key:关键字
function getHilightStrArray (str,key) {
  return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
}

 

推荐阅读