vue页面实现文本关键字检索,关键字高亮显示及定位功能

<template>
  <div class="search-highlight" v-html="contentShow">
  </div>
</template>

<script>
const PLUGIN_FLAG = 'search-hightlight_by_mumaa'

export default {
  props: {
    content: {
      type: String,
      default: ''
    },
    keyword: {
      type: String,
      default: ''
    },
    highlightStyle: {
      type: String,
      default: 'background: #ffff00'
    },
    currentStyle: {
      type: String,
      default: 'background: #ff9632'
    },
    regExp: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      lightIndex: 0,
      matchCount: 0,
      contentShow: '',
      random: `${Math.random()}`.slice(2)
    }
  },
  computed: {
    watchString () {
      return [this.content, this.keyword]
    },
    watchStyle () {
      return [this.lightIndex, this.highlightStyle, this.currentStyle]
    },
    flag () {
      return `${PLUGIN_FLAG}${this.random}`
    },
    styleSelector () {
      return `style[${this.flag}]`
    },
  },
  watch: {
    watchString: {
      immediate: true,
      handler () {
        this.replaceKeywords()
      }
    },
    watchStyle: {
      immediate: true,
      handler () {
        this.setStyle()
      }
    },
    lightIndex: {
      immediate: true,
      handler () {
        this.$emit('current-change', this.lightIndex)
      }
    },
    matchCount: {
      immediate: true,
      handler () {
        this.$emit('match-count-change', this.matchCount)
      }
    }
  },
  beforeDestroy () {
    this.clearStyle()
  },
  methods: {
    getTextNodeList (dom) {
      const nodeList = [...dom.childNodes]
      const textNodes = []
      while (nodeList.length) {
        const node = nodeList.shift()
        if (node.nodeType === node.TEXT_NODE) {
          node.wholeText && textNodes.push(node)
        } else {
          nodeList.unshift(...node.childNodes)
        }
      }
      return textNodes
    },

    getTextInfoList (textNodes) {
      let length = 0
      const textList = textNodes.map(node => {
        let startIdx = length, endIdx = length + node.wholeText.length
        length = endIdx
        return {
          text: node.wholeText,
          startIdx,
          endIdx
        }
      })
      return textList
    },

    getMatchList (content, keyword) {
      if (!this.regExp) {
        const characters = [...'\\[](){}?.+*^$:|'].reduce((r, c) => (r[c] = true, r), {})
        keyword = keyword.split('').map(s => characters[s] ? `\\${s}` : s).join('[\\s\\n]*')
      }
      const reg = new RegExp(keyword, 'gmi')
      const matchList = []
      let match = reg.exec(content)
      while (match) {
        matchList.push(match)
        match = reg.exec(content)
      }
      return matchList
    },

    replaceMatchResult (textNodes, textList, matchList) {
      // 对于每一个匹配结果,可能分散在多个标签中,找出这些标签,截取匹配片段并用font标签替换出
      for (let i = matchList.length - 1; i >= 0; i--) {
        const match = matchList[i]
        const matchStart = match.index, matchEnd = matchStart + match[0].length // 匹配结果在拼接字符串中的起止索引
        // 遍历文本信息列表,查找匹配的文本节点
        for (let textIdx = 0; textIdx < textList.length; textIdx++) {
          const { text, startIdx, endIdx } = textList[textIdx] // 文本内容、文本在拼接串中开始、结束索引
          if (endIdx < matchStart) continue // 匹配的文本节点还在后面
          if (startIdx >= matchEnd) break // 匹配文本节点已经处理完了
          let textNode = textNodes[textIdx] // 这个节点中的部分或全部内容匹配到了关键词,将匹配部分截取出来进行替换
          const nodeMatchStartIdx = Math.max(0, matchStart - startIdx) // 匹配内容在文本节点内容中的开始索引
          const nodeMatchLength = Math.min(endIdx, matchEnd) - startIdx - nodeMatchStartIdx // 文本节点内容匹配关键词的长度
          if (nodeMatchStartIdx > 0) textNode = textNode.splitText(nodeMatchStartIdx) // textNode取后半部分
          if (nodeMatchLength < textNode.wholeText.length) textNode.splitText(nodeMatchLength)
          const font = document.createElement('font')
          font.setAttribute(this.flag, i + 1)
          font.innerText = text.substr(nodeMatchStartIdx, nodeMatchLength)
          textNode.parentNode.replaceChild(font, textNode)
        }
      }
    },

    replaceKeywords () {
      let errFlag = false
      if (this.regExp) {
        try {
          const reg = new RegExp(this.keyword)
          if (reg.test('')) errFlag = true
        } catch (err) {
          errFlag = true
        }
      }
      if (errFlag || !this.keyword) {
        this.contentShow = this.content
        return
      }
      const div = document.createElement('div')
      div.innerHTML = this.content
      const textNodes = this.getTextNodeList(div)
      const textList = this.getTextInfoList(textNodes)
      const content = textList.map(({ text }) => text).join('')
      const matchList = this.getMatchList(content, this.keyword)
      this.matchCount = matchList.length
      this.lightIndex = this.matchCount ? 1 : 0
      this.replaceMatchResult(textNodes, textList, matchList)
      this.contentShow = div.innerHTML
    },
    scrollTo (index) {
      this.$nextTick(() => {
        let node = this.$el.querySelector(`font[${this.flag}='${index}']`)
        if (node) {
          this.lightIndex = index
          node.scrollIntoView()
        }
      })
    },
    searchNext () {
      this.$nextTick(() => {
        let idx = this.lightIndex >= this.matchCount ? 1 : this.lightIndex + 1
        this.scrollTo(idx)
      })
    },
    searchLast () {
      this.$nextTick(() => {
        let idx = this.lightIndex <= 1 ? this.matchCount : this.lightIndex - 1
        this.scrollTo(idx)
      })
    },
    setStyle () {
      let style = document.head.querySelector(this.styleSelector)
      if (!style) {
        style = document.createElement('style')
        style.setAttribute(this.flag, 1)
      }
      style.innerText = `font[${this.flag}]{${this.highlightStyle}}font[${this.flag}='${this.lightIndex}']{${this.currentStyle}}`
      document.head.appendChild(style)
    },
    clearStyle () {
      let style = document.head.querySelector(this.styleSelector)
      style && document.head.removeChild(style)
    }
  }
}
</script>

以下是demo

<template>
  <div id="app">
    <div class="container">
      <div class="header">
        <input type="text" v-model="keyword">
        <div class="match-num">{{ currentIdx }} / {{ matchCount }}</div>
        <button @click.stop="searchLast">上一个</button>
        <button @click.stop="searchNext">下一个</button>
      </div>
      <search-highlight
        class="search-highlight"
        ref="search"
        @current-change="currentChange"
        @match-count-change="matchCountChange"
        :content="content"
        regExp
        :keyword="keyword">
      </search-highlight>
    </div>
  </div>
</template>

<script>
import SearchHighlight from './components/SearchHighlight.vue'

export default {
  name: 'app',
  components: {
    SearchHighlight
  },
  data () {
    return {
      keyword: '明月',
      currentIdx: 0,
      matchCount: 0,
      content: `
            春江花月夜
                [唐] 张若虚
      春江潮水连海平,海上明<b>月</b>共潮生。
      滟滟随波千万里,何处春江无月明!
      江流宛转绕芳甸,月照花林皆似霰;
      空里流霜不觉飞,汀上白沙看不见。
      江天一色无纤尘,皎皎空中孤月轮。
      江畔何人初见月?江月何年初照人?
      人生代代无穷已,江月年年望相似。
      不知江月待何人,但见长江送流水。
      白云一片去悠悠,青枫浦上不胜愁。
      谁家今夜扁舟子?何处相思明<b>月</b>楼?
      可怜楼上月徘徊,应照离人妆镜台。
      玉户帘中卷不去,捣衣砧上拂还来。
      此时相望不相闻,愿逐月华流照君。
      鸿雁长飞光不度,鱼龙潜跃水成文。
      昨夜闲潭梦落花,可怜春半不还家。
      江水流春去欲尽,江潭落月复西斜。
      斜月沉沉藏海雾,碣石潇湘无限路。
      不知乘月几人归,落月摇情满江树。`,
    }
  },
  mounted () {
    let keywords = ['明月', '江', '春']
    const map = [...'\\[](){}?.+*^$:|'].reduce((r, c) => (r[c] = true, r), {})
    keywords = keywords.filter(word => word).map(word => {
      return word.split('').map(s => map[s] ? `\\${s}` : s).join('[\\s\\n]*')
    })
    this.keyword = keywords.join('|')
  },
  methods: {
    searchLast () {
      this.$refs.search.searchLast()
    },
    searchNext () {
      this.$refs.search.searchNext()
    },
    matchCountChange (count) {
      this.matchCount = count
    },
    currentChange (idx) {
      this.currentIdx = idx
    },
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  display: flex;
}
body {
  margin: 0;
}

</style>

<style>

.container {
  max-width: 30rem;
  height: 100vh;
  box-sizing: border-box;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  text-align: center;
  display: flex;
  height: 40px;
  align-items: center;
  flex-shrink: 0;
  flex-wrap: wrap;
}

button {
  margin: 0 2px;
  flex-shrink: 0;
}

.search-highlight {
  flex: auto;
  max-height: 20em;
  white-space: pre-line;
  overflow: auto;
  line-height: 2em;
}
</style>

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Vue 中的搜索框中输入关键字后,将匹配到的内容高亮显示,可以遵循以下步骤: 1. 在 data 中定义一个变量来保存搜索关键字。 2. 在模板中使用 input 元素来渲染搜索框,并为其绑定一个 input 事件来监听输入内容变化。 3. 在模板中渲染需要搜索的内容,并使用 v-html 指令将内容渲染为 HTML。 4. 使用 computed 属性来实现关键字高亮的逻辑。在 computed 中定义一个方法,接收需要搜索的内容和搜索关键字,并使用正则表达式将匹配到的内容用 <span> 标签包裹,从而达到高亮的效果。 以下是一个示例代码: ``` <template> <div> <input type="text" v-model="searchText" @input="highlightText" placeholder="请输入搜索关键字"> <div v-html="highlightedContent"></div> </div> </template> <script> export default { data() { return { searchText: '', content: '这是一段需要搜索的内容,其中包含关键字 Vue 和高亮。' } }, computed: { highlightedContent() { const regex = new RegExp(this.searchText, 'gi') return this.content.replace(regex, '<span class="highlight">$&</span>') } }, methods: { highlightText() { // 触发 computed 中的方法 } } } </script> <style> .highlight { color: red; font-weight: bold; } </style> ``` 在这个示例中,我们在 data 中定义了 searchText 和 content 两个变量,其中 content 是需要搜索的内容。在模板中使用 input 元素来渲染搜索框,并使用 v-model 将输入的内容绑定到 searchText 上,在 input 事件中触发 highlightText 方法。使用 v-html 指令将 computed 中返回的内容渲染为 HTML。在 computed 中定义了一个方法 highlightedContent,使用正则表达式将匹配到的内容用 span 标签包裹。最后在样式中定义了高亮的样式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值