参考文章:https://www.jianshu.com/p/86d73745e01c
由于最近本公司要开发一个小程序,有一个列表搜索需要实现搜索关键字高亮的效果,然后我就去网上百度了一波,然后自己也写了一下,感觉实现起来还是比较简单的,记录一下。
先放上效果图:
我这里是放的基金名称和基金id的数据,所以凡是出现我输入的内容,都会高亮
index.js
//获取应用实例
const app = getApp();
const getInf = (str, key) => str.toString().replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
Page({
data: {
keyName: null,
listData: [
{"id":"1", "fund_id": "150084", "fund_name": "广发深证100指数分级B" },
{ "id": "2", "fund_id": "450011", "fund_name": "国富研究精选混合" },
{ "id": "3", "fund_id": "000008", "fund_name": "嘉实中证500ETF联接" },
{ "id": "4", "fund_id": "050021", "fund_name": "博时深证基本面200ETF联接" },
{ "id": "5", "fund_id": "150064", "fund_name": "长盛同瑞A" },
{ "id": "6", "fund_id": "150136", "fund_name": "国富中证100指数增强分级B" },
{ "id": "7", "fund_id": "150049", "fund_name": "南方新兴消费收益" },
], // 内容原始数组
listDataCopy: [], // 用来搜索的复制数组
// 为什么要用两个数组就是,原始数组是不能改变的,我们每次输入关键字都要拿原始数组来处理,然后拆分成需要的数据去展示
},
onReady: function (e) {
var that = this;
},
onLoad: function (e) {
var that = this;
that.searchTap();
},
// 输入框正在输入
bindInput: function (e) {
var that = this;
that.setData({
keyName: that.trim(e.detail.value)
})
that.searchTap();
},
// 搜索关键字
searchTap: function () {
var that = this;
that.setData({
listDataCopy: that.data.listData
})
var data = that.data.listData;
var newData = that.data.listDataCopy;
for (var i = 0; i < data.length; i++) {
var dic = data[i];
var newDic = newData[i];
var fund_name = dic["fund_name"];
newDic["fund_name"] = getInf(fund_name, that.data.keyName);
var fund_id = dic["fund_id"];
newDic["fund_id"] = getInf(fund_id, that.data.keyName);
}
that.setData({
listDataCopy: newData,
})
},
// 去除首尾的空格
trim: function (s) {
return s.replace(/(^\s*)|(\s*$)/g, "");
}
})
index.wxss
.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: #ff0000;
}
.oneText {
line-height: 50rpx;
margin: 15;
text-align: left;
color: #9B9B9B;
font-size: 32rpx;
text-indent:1rem;
}
.currentText {
color: #0099FF;
}
index.wxml
<view class="section">
<view class="view-search">
<input class="view-search-input" value="{{keyName}}" placeholder="输入搜索关键词" bindinput="bindInput" maxlength="11" />
</view>
<view wx:for="{{listDataCopy}}" wx:key="*this" style='border:1rpx solid #FAFAFA;'>
<view class='oneText'>
<text wx:for="{{item.fund_name}}" wx:key="{{index}}" class="{{item == keyName ? 'searchHigh' : '' }}">{{item}}</text>
</view>
<view class='oneText'>
<text wx:for="{{item.fund_id}}" wx:key="{{index}}" class="{{item == keyName ? 'searchHigh' : '' }}">{{item}}</text>
</view>
</view>
</view>
当然,如果大家想结合接口也是可以的。
最后,如有错误,望纠正。
若有更好的方法,欢迎一起交流