記事ディレクトリ
マッチ交換
this.keyWords:Vueフレームワークに入力されたキーワード(キーワードに応じて対応する位置に移動)
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:はすべての一致したキーワードの結果です(一致して置換すると、一致したすべてのコンテンツは、resultという名前のスパンタグで設定されるため、querySelectorAllを介して取得したすべてのコンテンツを取得できます)
。モジュールです。ジャンプすると、検索コンテンツと上部の間の距離が得られます。直接ジャンプすると、検索モジュールで覆われるため、通常どおりジャンプして検索コンテンツを表示するには、検索モジュールの高さを引く必要があります。
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",
});
}
最後に完全なデモを投稿する
<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>