微信小程序搜索关键词高亮效果(转)
目录结构
search.html页面
<view class="search">
<input focus='auto' bindinput="searchInputAction" placeholder="输入你要搜索的内容" />
</view>
<!-- 搜索时内容 -->
<view wx:if="{{searchResultDatas.length > 0}}" class="search-content-body">
<block wx:for="{{searchResultDatas}}">
<view class="search-result-item">
<searchHighlightTextView
class="result-item"
datas='{{searchData[index]}}'
bindtap="chooseSearchResultAction"
data-id='{{item.ganhuo_id}}'
/>
</view>
</block>
</view>
// pages/search/search.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 输入监听
*/chooseSearchResultAction(e){
console.log(e)
},
searchInputAction: function (e) {
console.log(e)
let that = this
let value = e.detail.value
if (value.length == 0) {
this.setData({
searchResultDatas: []
})
return
}
wx.request({
url: 'https://gank.io/api/search/query/' + value + '/category/all/count/10/page/1',
data: '',
success: function (res) {
console.log(res)
let searchData = res.data.results.map(function(res){
return { key: value,name:res.desc}
})
that.setData({
searchData,
searchResultDatas: res.data.results
})
},
fail: function (res) { },
})
},
})
/* pages/search/search.wxss */
.search {
margin: 50rpx;
border: 1rpx solid #eee;
padding: 20rpx;
}
.search-content-body {
margin: 50rpx;
}
search.JSON
{
"usingComponents": {
"searchHighlightTextView": "../../component/searchHighlightTextView/searchHighlightTextView"
},
"navigationBarTitleText": "搜索"
}
searchHighlightTextView组件
<!--component/searchHilightTextView.wxml-->
<view>
<text wx:for="{{searchArray}}" wx:key="*this" class="{{item == keyName ? 'highlight' : 'normal' }}">{{item}}</text>
</view>
// component/searchHilightTextView.js
Component({
/**
* 组件的属性列表
*/
properties: {
/**
* {key:'关键字',name:'待匹配字符串'}
*/
datas: {
type: Object,
observer: "_propertyDataChange"
}
},
/**
* 组件的初始数据
*/
data: {
searchArray: [],
keyName: ''
},
/**
* 组件的方法列表
*/
methods: {
_propertyDataChange: function(newVal) {
console.log(newVal)
let searchArray = this.getHilightStrArray(newVal.name, newVal.key)
this.setData({
keyName: newVal.key,
searchArray: searchArray
})
},
getHilightStrArray: function(str, key) {
return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
}
},
})
/* component/searchHilightTextView.wxss */
text {
height: 40rpx;
font-family: PingFangSC;
font-size: 28rpx;
font-weight: normal;
font-style: normal;
font-stretch: normal;
line-height: normal;
letter-spacing: normal;
}
.highlight {
color: hotpink;
}
.normal {
color: #484848;
}
searchHighlightTextView组件 JSON
{
"component": true,
"usingComponents": {}
}