vue2 项目,有一个项目详情页,详情页内由上到下有5个模块进行排列,要求封装一个固定于右侧竖向排列的快速定位标签,点击标签页面滚动到相应的模块,并且页面上下滚动标签联动高亮的功能
时间: 2023-12-25 19:03:40 浏览: 16
可以使用 Vue 的自定义指令来实现这个功能。
首先,在组件中添加一个用来标识模块的属性,例如 `data-scroll-target="module1"`。
然后,创建一个自定义指令 `scroll`,在这个指令中监听标签的点击事件,获取目标模块的位置信息,然后使用 `window.scrollTo` 方法来滚动页面。同时,监听页面滚动事件,根据滚动位置来判断当前应该高亮哪个标签。
代码示例:
```html
<template>
<div>
<div v-scroll="module1" data-scroll-target="module1">模块1</div>
<div v-scroll="module2" data-scroll-target="module2">模块2</div>
<div v-scroll="module3" data-scroll-target="module3">模块3</div>
<div v-scroll="module4" data-scroll-target="module4">模块4</div>
<div v-scroll="module5" data-scroll-target="module5">模块5</div>
</div>
</template>
<script>
export default {
directives: {
scroll: {
inserted: function (el, binding) {
el.addEventListener("click", function () {
const target = document.querySelector(
`[data-scroll-target="${binding.value}"]`
);
const targetRect = target.getBoundingClientRect();
const scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
const targetTop = targetRect.top + scrollTop;
window.scrollTo({
top: targetTop,
behavior: "smooth",
});
});
},
update: function (el, binding) {
const target = document.querySelector(
`[data-scroll-target="${binding.value}"]`
);
const targetRect = target.getBoundingClientRect();
const scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
const targetTop = targetRect.top + scrollTop;
const windowHeight = window.innerHeight;
const isTop =
scrollTop + windowHeight >= document.documentElement.scrollHeight;
const isActive =
targetTop <= scrollTop + windowHeight / 2 &&
(isTop || targetTop + targetRect.height > scrollTop);
el.classList.toggle("active", isActive);
},
},
},
};
</script>
<style>
.active {
color: red;
}
</style>
```
在上面的代码中,我们使用了 `inserted` 钩子函数来监听标签的点击事件,使用 `update` 钩子函数来监听页面的滚动事件。在 `update` 函数中,我们首先获取目标模块的位置信息,然后根据滚动位置和窗口高度来判断当前应该高亮哪个标签。最后,我们使用 `classList.toggle` 方法来动态添加或移除 `active` 类名,以实现标签联动高亮的效果。