Vue2实现浏览器ctrl+f功能

Vue2实现浏览器ctrl+f功能

插件github地址

https://github.com/WenyaoL/search-bar-vue2

如果需要的话可以fork下来,自己改一下插件的代码,代码原理就是遍历dom节点,然后修改节点中文本(用一个新的span标签包围选中的文本)。

一般浏览器都自带ctrl+f功能的,当初写这个代码时,主要是为了PC端(electron应用)桌面应用写的搜索功能。

安装插件

使用一个Vue2的插件search-bar-vue2

npm install search-bar-vue2

全局注册

//全局注册
import SearchBar from 'search-bar-vue2'
Vue.use(SearchBar)

局部注册

<template>
  <div>
    <search-bar :root="'#app'" 
                :highlightClass="'myHighLight'" 
                :selectedClass="'selected-highlight'" 
                :hiden.sync="showSearchBar"/>
    <button @click="searchClick()">搜索按钮</button>
    <div id="app">
        <!--文档-->
      <document/>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Document from './components/Document.vue';
import {searchBar} from 'search-bar-vue2'
export default Vue.extend({
  name: 'App',
  components: {
    Document,
    searchBar
  },
  data(){
    return{
      showSearchBar:false
    }
  },
  methods:{
    searchClick(){
      
      this.showSearchBar = !this.showSearchBar
      console.log("切换showSearchBar",this.showSearchBar);
    }
  }
});
</script>

<style>
.myHighLight{/*自定义高亮背景*/
  background-color: yellow;
}
.selected-highlight{/*自定义选中高亮背景*/
  background-color: yellowgreen;
}
</style>

展示

请添加图片描述

posted @   鸭梨的药丸哥  阅读(244)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示