当前位置:网站首页>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>
边栏推荐
猜你喜欢

Handwritten virtualdom

ThinkPHP 6 使用 mongoDB

记微信小程序setData动态修改字段名

YOLO Nano:一种高度紧凑的只看一次的卷积神经网络用于目标检测

keras转tf.keras中VGG19 input_shape

SSD improvements cfenet

SSD改進CFENet

记自定义微信小程序顶部导航栏

July 2022 (advanced soft test) information system project manager certification enrollment Brochure

Keras to tf Vgg19 input in keras_ shape
随机推荐
Pointnet的网络学习
Pointnet/pointnet++ training and testing
SSD改进CFENet
Did you really make things clear when you were promoted or reported?
Verilog reduction operator
记微信小程序setData动态修改字段名
MT-yolov6训练及测试
微信小程序自定义多项选择器
ThinkPHP 6 使用 mongoDB
Unity C# 网络学习(十二)——Protobuf生成协议
PointNet/Pointnet++训练及测试
MySQL row column conversion example
抽象类、接口
微信小程序wx.navigateBack返回上一页携带参数
网络安全问题
Instance error iopub data rate exceeded
MySQL virtual column
在 golang 中是如何对 epoll 进行封装的?
YOLACT实时实例分割
Picture format -webp