小程序中搜索文字高亮顯示
阿新 • • 發佈:2018-12-27
get 請求 高亮 current length split NPU primary box
小程序對解析標簽字符串不友好,有時候要處理一些搜索內容、關鍵字、段落中高亮展示檢索到的匹配文字就會比較麻煩。
[HTML]
<view class="section"> <view class="view-search"> <input class="view-search-input" value="{{keyName}}" placeholder="輸入搜索關鍵詞" bindinput="bindInput" maxlength="11" /> </view> <scroll-view class="scrollView" scroll-y> <view wx:for="{{searchDataList}}" wx:key="*this"> <view class=‘oneText‘> <text wx:for="{{item.text}}" wx:key="{{index}}" class="{{item == keyName ? ‘searchHigh‘ : ‘‘ }}">{{item}}</text> </view> </view> </scroll-view> </view>
[CSS]
.view-search { padding: 12rpx 30rpx; box-sizing: border-box; position: relative; } .view-search-input { height: 70rpx; line-height: 70rpx; border: 2rpx solid #ccc; border-radius: 10rpx; box-sizing: border-box; padding: 0px 70rpx 0px 20rpx; font-size: 32rpx; } .searchHigh { color: #409eff; } .scrollView { height: 80vh; background-color: #F5F5F5; box-sizing: border-box; } .oneText { line-height: 50rpx; margin: 30rpx; text-align: center; color: #9B9B9B; font-size: 32rpx; } .currentText { color: #0099FF; }
[JavaScript]
const app = getApp(); const getInf = (str, key) => str.replace(new RegExp(`${key}`, ‘g‘), `%%${key}%%`).split(‘%%‘); Page({ data: { keyName: null, primaryListData: [ { "id": "1", "text": "挺不錯的小老弟" }, { "id": "2", "text": "是的,挺不錯" }, ], // 內容原始數組 (如果是後臺請求的數據,就不需要兩個數組了)) searchDataList: [ { "id": "1", "text": "挺不錯的小老弟" }, { "id": "2", "text": "是的,挺不錯" }, ], // 用來搜索的復制數組 }, // 輸入框正在輸入 bindInput: function (e) { var that = this; that.setData({ keyName: that.trim(e.detail.value) }) that.searchTap(); }, // 搜索關鍵字 searchTap: function () { var that = this; var data = that.data.primaryListData; var newData = that.data.searchDataList; for (var i = 0; i < data.length; i++) { var dic = data[i]; var newDic = newData[i]; var text = dic["text"]; newDic["text"] = getInf(text, that.data.keyName); } that.setData({ searchDataList: newData, }) }, // 去除首尾的空格 trim: function (s) { return s.replace(/(^\s*)|(\s*$)/g, ""); }, onLoad: function (e) { }, })
小程序中搜索文字高亮顯示