文章目录
匹配替换
this.keyWords:在 vue 框架中 input 的关键词(根据关键词定位到对应位置)
this.article:文章内容(在文章中检索关键字并定位)
let regExp = new RegExp(this.keyWords, "g");
this.article = this.article.replace(
regExp,
'<span class="result" style="background:yellow;color:red;">' +
this.keyWords +
"</span>"
);
跳转对应位置
mainCContainer:是匹配出的所有关键词结果(在匹配替换的时候,将所有匹配到的内容都套了一个 class名为 result 的 span 标签,所以可以通过 querySelectorAll 拿到所有检索内容)
search :是顶部搜索模块,因为跳转的时候获取的是检索内容距离顶部距离,如果直接跳转会被搜索模块遮住,所以需要减去搜索模块的高度,才能正常跳转并看到我们的检索内容
let mainContainer = document.querySelectorAll(".result");
let search = document.querySelector("#search");
if (mainContainer.length == 0) {
fn();
} else {
window.scrollTo({
top:
mainContainer[checkIndex].offsetTop -
search.clientHeight,
behavior: "smooth",
});
}
最后贴出完整demo
<template>
<div class="home" style="margin: 0">
<div
id="search"
style="position:fixed; top :0;background: #fff;width:100%;padding: 20px 0;"
>
<el-input type="search" v-model="keyWords" placeholder="请输入搜索内容" style="width:200px;"></el-input>
<el-button style="margin-left: 10px" @click="search">搜索</el-button>
<el-button type="success" @click="next" style="margin-top: 20px">下一个</el-button>
<el-button type="warning" @click="previous" style="margin-top: 20px">上一个</el-button>
</div>
<div class="contet" id="content" style="margin-top: 100px" v-html="article"></div>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
myData:""
keyWords: "",
article: "",
checkIndex: 0,
};
},
mounted() {
this.article = this.myData;
},
methods: {
search() {
this.checkIndex = 0;
this.article = this.myData;
let allNum = 0;
let regExp = new RegExp(this.keyWords, "g");
this.article = this.article.replace(
regExp,
'<span class="result" style="background:yellow;color:red;">' +
this.keyWords +
"</span>"
);
this.scrollToLocation(this.checkIndex);
},
next() {
this.checkIndex++;
this.scrollToLocation(this.checkIndex);
},
previous() {
this.checkIndex--;
this.scrollToLocation(this.checkIndex);
},
scrollToLocation(checkIndex) {
fn();
// 这里使用定时的原因是因为第一次跳转的时候 dom 还在渲染,不一定能获取到,所以需要利用定时器多次获取
function fn() {
setTimeout(() => {
let mainContainer = document.querySelectorAll(".result");
let search = document.querySelector("#search");
if (mainContainer.length == 0) {
fn();
} else {
window.scrollTo({
top:
mainContainer[checkIndex].offsetTop -
search.clientHeight,
behavior: "smooth",
});
}
}, 300);
}
},
}
};
</script>