在小程序中做搜索功能時,有需求要將搜索的文字標記爲藍色。
實現方式:
1.使用小程序組將rich-text,將內容用正則匹配並用<span style="color:#1D57D8">${this.inputValue}</span>替換
<rich-text :nodes="item.articleLabel"></rich-text>
i.categoryLabel = this.setColor(i.categoryName)
setColor(str) {
let s = `<span style="color:#1D57D8">${this.inputValue}</span>`
let text = str.replace(new RegExp(this.inputValue,'g'),s)
return text
}
2.使用text,將內容用搜索的文字分割,這個方法可以對標記的內容添加事件。
<text v-if="it.descLabel[0]">{{it.descLabel[0]}}</text>
<text style="color:#1D57D8" @click="goProduct(it.pbId)">{{it.keyword}}</text>
<text v-if="it.descLabel[1]">{{it.descLabel[1]}}</text>
x.descLabel = this.setColor('- '+x.description,x.keyword)
setColor(str,key) {
let s1 = str.split(key)[0]
let s2 = str.split(key)[1]
return [s1,s2]
}