当前位置:网站首页>Wechat applet search keyword highlighting and ctrl+f search positioning
Wechat applet search keyword highlighting and ctrl+f search positioning
2022-06-29 09:17:00 【swag_ Special actor】
principle
Highlight keywords
- Store text in an array , With
textLabel loop rendering , When there are keywordskeywordwhen , Replace the keyword of the text with%%keyword%%Re segmentationsplitArray to render . - The current node text is equal to the keyword
class="{ { item == searchValue ? 'searchHigh' : ''}}"when , add tohighLightstyle .
———————————————————————————————————————————
Here you can highlight the keyword .
Be similar to ctrl+f Search location
- There is no way for small programs to operate
domThe element does not return something like web It's the samedom node. - Render for all loops
text labeladdid. - utilize
wx.createSelectorQuery().selectAll('.searchHigh').boundingClientRectGet all addedhighLightNodes of stylesid Array - Array of
lengthIs the total number of keywords found , Create aactiveNodeIndexControl the previous and next . - When
text labelOfidAnd the arrayChoose idPhase at the same time , Add the checkselectedstyle . - You can use
scrollviewOfscrollIntoView(selector)Scroll to the selected node , Premise isscrollviewOfenhancedProperty to betrue. - It can also be used.
wx.pageScrollTo. It depends on the scenario you use .
effect 
Source code (mpx)
<template>
<view class="container">
<van-search id="searchPanel" value="{
{ searchValue }}" placeholder=" Please enter search keywords " bind:change="inpChange" />
<view class="statistic-bar">
<text> The first {
{ current }} strip </text>
<text> common {
{ totalKeywordNodes }} strip </text>
<text style="color: #1d84f6" bindtap="handleScroll('pre')"> Last article </text>
<text style="color: #1d84f6" bindtap="handleScroll('next')"> The next one </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">
<text wx: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, // Scrolling container nodes newList: [ {
title: ' About the way in which robot competitions are held, there are more wins than losses ', jj: ' The temperature at the Central Meteorological Observatory UIuouoiuo Water and electricity expenses the water and electricity expenses of the other party incurred by the company ' }, {
title: ' Close the odd and even I odd and even hi Vomit and shout after me and the odd and even ', jj: ' Inside kjlkjljk Defensive play you are letting go of the situation that you have nothing to do and left your parents. You have not considered paying for water and electricity in an all-round way ' }, {
title: ' About the extra day of fighting, let you steal Irene Of ', jj: ' The Central Meteorological Observatory issued the blue warning of cold wave today 20 these 8 Japan 20 Water and electricity charges water and electricity charges incurred by the company ' }, {
title: ' About the identity and oneness of Gerrit uyiuyiuyiuyiiuoui Win more and lose less ', jj: ' Content introduction I decouple my odd and even I I am beaten King Penguin sellers go to the water and electricity charges of Weng Qun, an evil mosquito repellent in Pall ' } ], keywordNodes: [], // Stored keyword nodes ID Array activeNodeIndex: 0 // Currently active node index }, 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 = this wx.getSystemInfo({
success (res) {
that.setData({
mainHeight: res.windowHeight }) } }) }, getFields () {
const that = this const query = wx.createSelectorQuery() query.select('#searchPanel').fields({
dataset: true, size: true }, res => {
// console.log(res) that.setData({
seachPanelHeight: res.height }) }).exec() }, // Replace keywords and split into arrays getInf (str, key) {
return str .replace(new RegExp(`${
key}`, 'g'), `%%${
key}%%`) .split('%%') .filter(item => {
if (item) {
return true } return false }) }, // Triggered when the input changes inpChange (e) {
let key = e.detail this.setData({
activeNodeIndex: 0, keywordNodes: [], searchValue: e.detail }) // If the keyword has a value, traverse the news list if (key) {
this.newList.forEach(element => {
// If the field is already an array, it becomes a string again if (element.jj instanceof Array) {
element.jj = element.jj.join('') } let newContent2 = this.getInf(element.jj, key) // Assign a value to each item of the divided array title element.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 Scroll the node to the visual window * @param {number} index */ scrollToView (index) {
// console.log("#" + this.keywordNodes[index]); this.$nextTick(() => {
this.scrollView.scrollIntoView("#" + this.keywordNodes[index]) }) }, /** * @method Control the previous and next * @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": " Search keyword highlighting ", "usingComponents": {
"van-search": "@vant/weapp/dist/search/index" } } </script>
边栏推荐
- verilog 等价操作符
- Pat (basic level) practice (Chinese) 1003 I want to pass! (20 points) C language implementation
- Instance error iopub data rate exceeded
- 笔试题“将版本号从大到小排列”
- Augfpn: improved multiscale feature learning for target detection
- verilog 移位操作符
- Mysql使用union all统计多张表组合总数,并分别统计各表数量
- Jar package and war package
- Uni app gets the route URL of the current page
- 来个小总结吧
猜你喜欢
随机推荐
记一些笔试题
[target detection] | indicator a probabilistic challenge for object detection
MT yolov6 training and testing
MySQL virtual column
Wechat applet jump to official account image and text content
Debugging H5 page -weinre and spy debugger real machine debugging
训练查看(问题暂存)
微信小程序项目:微信小程序页面布局
mysql insert 时出现Deadlock死锁场景分析
verilog 等价操作符
在 RedisTemplate 中使用 scan
【To .NET】C#数据模型,从Entity Framework Core到LINQ
记自定义微信小程序顶部导航栏
CMD enter virtual machine
Network security issues
Open3d hidden point removal
Verilog size and +: Using
Training view (issue temporary storage)
Detecting and counting tiny faces
Let's make a summary









