/* 比如你有若干个div 名字都叫section */
<div class="section" ref="sections-1"></div>
<div class="section" ref="sections-2"></div>
<div class="section" ref="sections-3"></div>
<div class="section" ref="sections-4"></div>
<div class="section" ref="sections-5"></div>
<div class="section" ref="sections-6"></div>
2. 在vue的mounted生命周期中
mounted(){
this.$nextTick(() => {
const options = {
root: null, // 指定根元素,这里设为 null,表示选取整个视窗作为根元素。
rootMargin: "0px", // 指定根元素的边界,这里设为 "0px",表示根元素的边界和视窗的边界重合
threshold: 0.5, // 指定交叉比例,这里设为 0.5,表示当目标元素一半或更多显示在视窗中时触发回调函数。
};
const callback = (entries, observer) => {
//entries:代表观察到的目标元素的集合。 observer:代表观察者对象。
entries.forEach((entry) => {
//entry.isIntersecting:检查当前目标元素是否与根元素相交。
if (entry.isIntersecting) {
const target = entry.target;
//entry.target:获取当前目标元素
const sections = Array.from(document.querySelectorAll(".section"));
//sections:获取所有具有 .section 类名的元素,并转换为数组。
let index = sections.findIndex((section) => section === target) + 1;
//index:查找当前目标元素在 sections 数组中的索引,并加 1,用于确定当前页码。
}
});
};
// 创建一个新的 Intersection Observer 实例,用于观察目标元素和执行相应的回调函数。
// new IntersectionObserver(callback, options):使用之前定义的 callback 回调函数和 options 配置选项来初始化 Intersection Observer 实例。
// javascript
const observer = new IntersectionObserver(callback, options);
const sections = document.querySelectorAll(".section");
//observer 观察每个元素,以便在它们进入或离开视窗时触发回调函数。
sections.forEach((section) => {
observer.observe(section);
});
});
}
3.点击菜单栏跳转到某个div
toReg (pageIndex) {
//传入的index索引
this.$nextTick(() => {
const section = this.$refs[`sections-${pageIndex + 1}`];
if (section) {
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
}
4. 在上面的代码中index 就是进入了当前某个页面 1、2、3、4、5.....