微信小程序搜索关键字高亮和ctrl+f搜索定位实现
生活随笔
收集整理的這篇文章主要介紹了
微信小程序搜索关键字高亮和ctrl+f搜索定位实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原理
高亮關鍵字
- 將文本存入數組,以text標簽循環渲染,當有關鍵字keyword時,將文本的關鍵字替換成%%keyword%%再分割split成數組去渲染。
- 當前節點文本等于關鍵字 class="{{ item == searchValue ? 'searchHigh' : ''}}"時,添加highLight樣式。
———————————————————————————————————————————
到這里高亮關鍵字就實現了。
類似于ctrl+f搜索定位
- 小程序沒有辦法操作dom元素不會返回像web端一樣的dom節點。
- 給所有循環渲染的text標簽加上id。
- 利用 wx.createSelectorQuery().selectAll('.searchHigh').boundingClientRect獲取所有添加了highLight樣式的節點id數組
- 數組的length就是找到關鍵字的總數,創建一個activeNodeIndex控制上一條和下一條。
- 當text標簽的id和數組中取出的選中id相同時,添加選中selected樣式。
- 可以利用scrollview的scrollIntoView(selector)滾動到選中的節點,前提是scrollview的enhanced屬性要為true。
- 也可以用wx.pageScrollTo。具體看你使用的場景。
效果
源碼(mpx)
<template><view class="container"><van-searchid="searchPanel"value="{{ searchValue }}"placeholder="請輸入搜索關鍵詞"bind:change="inpChange"/><view class="statistic-bar"><text>第{{ current }}條</text><text>共{{ totalKeywordNodes }}條</text><text style="color: #1d84f6" bindtap="handleScroll('pre')">上一條</text><text style="color: #1d84f6" bindtap="handleScroll('next')">下一條</text></view><scroll-view scroll-y enhanced style="height: {{listHeight}}px" class="listPanel"><view class="news_item" wx:for="{{newList}}" wx:key="index"><view class="descBox"><view class="news_title textoverflow">{{ item.title }}</view><view class="news_text"><textwx:for="{{ item.jj }}"wx:for-index="secondIndex"wx:key="secondIndex"id="text_{{index + '_'+ secondIndex}}"class="{{ item == searchValue ? 'searchHigh' : ''}}"wx:class="{{ {selected: 'text_'+index + '_'+ secondIndex === keywordNodes[activeNodeIndex]} }}">{{ item }}</text></view></view></view></scroll-view></view> </template> <script> import { createPage } from '@mpxjs/core' createPage({data: {mainHeight: 0,seachPanelHeight: 0,searchValue: '',scrollView: null, // 滾動容器節點newList: [{title: '關于舉行機器人競賽活動的相所發生的方式勝多負少的',jj: '內容簡介中央氣象臺氣溫氣溫UIuouoiuo水電費水電費公司的發生的對方水電費'},{title: '關偶奇偶我奇偶就hi嘔吼我和奇偶以后后的',jj: '內kjlkjljk防守打法你是端放開那沒事的離開父母了情況沒考慮為全面方水電費'},{title: '關于額外日圍毆日頭誒讓你偷Irene的',jj: '內容簡介中央氣象臺發布寒潮藍色預警計今天20時至8日20時水電費水電費水電費公司的發生的對方水電費'},{title: '關于爾特瑞特認同與一體uyiuyiuyiuyiiuoui 勝多負少的',jj: '內容簡介我解耦我偶奇偶我我就挨打王企鵝賣家前往頗爾惡趣味驅蚊器翁群水電費'}],keywordNodes: [], // 存放的關鍵字節點ID數組activeNodeIndex: 0 // 當前激活的節點索引},computed: {listHeight () {return this.mainHeight - this.seachPanelHeight},totalKeywordNodes () {return this.keywordNodes.length},current () {if (this.keywordNodes.length === 0) {return 0} else {return this.activeNodeIndex + 1}}},onReady () {this.getWindowHeight()this.getFields()this.mockData()},methods: {mockData () {let temp = []for (let i = 0; i < 4; i++) {temp = temp.concat(this.newList)}this.setData({newList: temp})},getWindowHeight () {const that = thiswx.getSystemInfo({success (res) {that.setData({mainHeight: res.windowHeight})}})},getFields () {const that = thisconst query = wx.createSelectorQuery()query.select('#searchPanel').fields({dataset: true,size: true}, res => {// console.log(res)that.setData({seachPanelHeight: res.height})}).exec()},// 替換關鍵字并分割成數組getInf (str, key) {return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%').filter(item => {if (item) {return true}return false})},// 輸入改變時觸發inpChange (e) {let key = e.detailthis.setData({activeNodeIndex: 0,keywordNodes: [],searchValue: e.detail})// 如果關鍵字有值遍歷新聞列表if (key) {this.newList.forEach(element => {// 如果該字段已經是數組則重新變為字符串if (element.jj instanceof Array) {element.jj = element.jj.join('')}let newContent2 = this.getInf(element.jj, key)// 把分割的數組賦值給每一項的titleelement.jj = newContent2})// console.log(this.newList)this.$nextTick(() => {wx.createSelectorQuery().selectAll('.searchHigh').boundingClientRect(res => {let keywordNodes = res.map(item => item.id)this.setData({keywordNodes: keywordNodes})}).select('.listPanel').node(res => {this.setData({scrollView: res.node})this.scrollToView(0)}).exec()})}},/*** @method 將節點滾動至可視窗口* @param {number} index*/scrollToView (index) {// console.log("#" + this.keywordNodes[index]);this.$nextTick(() => {this.scrollView.scrollIntoView("#" + this.keywordNodes[index])})},/*** @method 控制上一條和下一條* @param {string} type*/handleScroll (type) {switch (type) {case 'pre':if (this.activeNodeIndex === 0) {this.activeNodeIndex = this.keywordNodes.length - 1} else {this.activeNodeIndex--}break;default:if (this.activeNodeIndex === this.keywordNodes.length - 1) {this.activeNodeIndex = 0} else {this.activeNodeIndex++}break;}this.scrollToView(this.activeNodeIndex)}} }) </script> <style scoped>.container {width: 100%;overflow: scroll;--webkit-overflow-scrolling: touch-action;}.statistic-bar {position: fixed;left: 16px;bottom: 30px;right: 16px;border-radius: 12rpx;background-color: #e6f7ff;z-index: 999;display: flex;justify-content: space-around;width: calc(100% - 16px -16px);padding: 16rpx 32rpx;box-sizing: border-box;font-size: 26rpx;box-shadow: 6rpx 6rpx 15rpx rgba(0, 0, 0, 0.125), -6rpx 0rpx 15rpx rgba(0, 0, 0, 0.125);color: #323233;}.listPanel {box-sizing: border-box;background-color: #f5f5f5;}.news_item {width: 100%;height: 208rpx;padding: 0 32rpx;margin: 32rpx 0;box-sizing: border-box;}.descBox {width: 100%;height: 100%;background: #fff;border-radius: 12rpx;padding: 24rpx;box-sizing: border-box;}.news_title {width: 100%;font-size: 32rpx;font-weight: 500;text-align: left;color: black;margin-bottom: 10rpx;}.news_text {font-size: 26rpx;font-weight: 400;color: #909090;text-align: left;margin-bottom: 7rpx;display: -webkit-box;-webkit-line-clamp: 2;overflow: hidden;text-overflow: ellipsis;-webkit-box-orient: vertical;word-break: break-all;}.textoverflow {display: -webkit-box;-webkit-line-clamp: 1;overflow: hidden;text-overflow: ellipsis;-webkit-box-orient: vertical;word-break: break-all;}.searchHigh {font-size: 36rpx;color: #1d84f6;font-weight: bold;}.selected {background: #909090;} </style> <script type="application/json">{"navigationBarTitleText": "搜索關鍵字高亮","usingComponents": {"van-search": "@vant/weapp/dist/search/index"}} </script>總結
以上是生活随笔為你收集整理的微信小程序搜索关键字高亮和ctrl+f搜索定位实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ARCSDE的直接连接(SQLSERVE
- 下一篇: 关于jrebel碰到的一次问题记录