显示锚点(纵横显示菜单)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下几个步骤实现: 1. 在菜单中添加点击事件,获取对应的锚点id。 2. 使用`ref`属性获取到内容容器的元素。 3. 在内容容器上绑定`scroll`事件,监听滚动位置。 4. 根据当前滚动位置,判断哪个锚点处于可视范围内,并高亮对应的菜单项。 具体代码如下: 菜单部分: ``` <template> <div> <ul> <li v-for="item in menu" :key="item.id" @click="scrollToAnchor(item.id)" :class="{active: activeAnchor === item.id}"> {{ item.title }} </li> </ul> </div> </template> <script> export default { data() { return { menu: [ { id: 'a1', title: '锚点1' }, { id: 'a2', title: '锚点2' }, { id: 'a3', title: '锚点3' } ], activeAnchor: '' // 当前激活的锚点id } }, methods: { scrollToAnchor(anchorId) { // 获取对应的锚点元素 const anchorElement = document.getElementById(anchorId); if (anchorElement) { // 滚动到锚点位置 anchorElement.scrollIntoView({ behavior: 'smooth' }); // 设置当前激活的锚点id this.activeAnchor = anchorId; } } } } </script> ``` 内容部分: ``` <template> <div ref="content" @scroll="onScroll"> <div id="a1">锚点1内容</div> <div id="a2">锚点2内容</div> <<div id="a3">锚点3内容</div> </div> </template> <script> export default { methods: { onScroll() { // 获取内容容器的高度和滚动位置 const contentHeight = this.$refs.content.offsetHeight; const scrollTop = this.$refs.content.scrollTop; // 遍历所有锚点,判断哪个处于可视范围内 for (let i = 0; i < this.menu.length; i++) { const anchorId = this.menu[i].id; const anchorElement = document.getElementById(anchorId); if (anchorElement) { const anchorTop = anchorElement.offsetTop; const anchorBottom = anchorTop + anchorElement.offsetHeight; if (scrollTop >= anchorTop && scrollTop < anchorBottom) { // 设置当前激活的锚点id this.$emit('active-anchor', anchorId); break; } } } } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值