效果图:
将搜索结果挨个格式化为数组,然后在渲染的时候判断type是否等于1,如果等于1,那就高亮显示。
主要代码:
<view class="address-title">
<text wx:for="{{item.titleArr}}" wx:key="*this" class="{{item.type === 1 ? 'highlight' : '' }}">{{item.text}}</text>
</view>
/**
*
* @param {字符串} content
* @param {关键字} key
* @param {结果} result
*/
getHighlightStrArray (content, key, result) {
if (result == undefined) {
result = [];
}
key = key.toUpperCase();
let keyLen = key.length;
let tmp = content.toUpperCase();
if (tmp.length >= keyLen && keyLen > 0) {
let index = -1;
index = tmp.indexOf(key);
if (index != -1) {
let text = content.substring(0, index);
result.push({
type: 2,
text: text
});
let keyText = content.substring(index, index + keyLen);
result.push({
type: 1,
text: keyText
});
content = content.substring(index + keyLen, content.length);
this.getHighlightStrArray(content, key, result);
} else {
result.push({
type: 2,
text: content
});
}
} else {
result.push({
type: 2,
text: content
});
}
return result;
},