模糊搜索时,搜索结果有时会需要将关键字设置为特别的颜色,方便进行区分,一下是实现方法:
wxml页面:
<block wx:for="{{title}}" wx:for-item="key_obj" wx:key="">
<text wx:if="{{key_obj.key == true}}" style="color:red;">{{key_obj.str}}</text>
<text wx:else>{{key_obj.str}}</text>
</block>
js文件:
hilight_word : function (key, word) {
let idx = word.indexOf(key);
let t = [];
if (idx > -1) {
if (idx == 0) {
t = this.hilight_word(key, word.substr(key.length));
t.unshift({ key: true, str: key });
return t;
}
if (idx > 0) {
t = this.hilight_word(key, word.substr(idx));
t.unshift({ key: false, str: word.substring(0, idx) });
return t;
}
}
return [{ key: false, str: word }];
},
_this.hilight_word(key,word)
直接调用即可,key标识关键字信息,word指的是完整信息
效果如图