微信小程序实现某个关键字高亮显示
需求: 实现对列表搜索的关键字进行高亮显示
- js
Page({
data: {
motto: '<高亮 A>',
list:[
'WaC38',
'W2A81',
'E2A18',
'E2A61',
'E3Ca1',
'E2C81',
'E4a43',
'E4A65'
]
},
onLoad: function () {
}
})
- wxml
<!--公共的wxs工具-->
<wxs src="../../wxs/highLight.wxs" module="util" />
<view class="container">
<view class="usermotto">
<text class="user-motto">{{motto}}</text>
</view>
<view wx:for="{{list}}" wx:key="item" >
<view wx:for="{{util.highLight(item,'A')}}" wx:key="item" style="float:left;">
<text wx:if="{{item.type==1}}" decode="true" space="true" style='color:red;'>{{util.myReplace(item.text)}} </text>
<text wx:else decode="true" space="true">{{util.myReplace(item.text)}}</text>
</view>
</view>
</view>
- wxs ---公共的处理高亮的方法
var sliceStr = function (str, len) {
var len = len || 8;
if (str != null) {
if (str.length > len) {
return str.substring(0, len) + "...";
} else {
return str;
}
}
return '';
}
var highLight = function (content, key, res) {
if (res == undefined) {
res = [];
}
key = key.toUpperCase();
var keyLen = key.length;
var tmp = content.toUpperCase();
if (tmp.length >= keyLen && keyLen > 0) {
var index = -1;
index = tmp.indexOf(key);
if (index != -1) {
var n = content.substring(0, index);
res.push({
type: 2,
text: n
});
var y = content.substring(index, index + keyLen);
res.push({
type: 1,
text: y
});
content = content.substring(index + keyLen, content.length);
highLight(content, key, res);
} else {
res.push({
type: 2,
text: content
});
}
} else {
res.push({
type: 2,
text: content
});
}
return res;
}
var myReplace = function (content) {
content = content.replace(" ", " ");
if (content.indexOf(" ") != -1) {
return myReplace(content);
}
return content;
}
module.exports.myReplace = myReplace;
module.exports.highLight = highLight;
module.exports.sliceStr = sliceStr;
image.png运行结果
网友评论