如何实现点击目录跳转到指定位置?【vue】

需求:实现目录点击跳转到指定位置,点击后直接定位到指定模块

效果:

实现方法:

(1)a标签跳转

     普通使用:

<!DOCTYPE html>
<html>
	<head>
		<title>a-Demo</title>
	</head>
	<style>
		/* bar超出屏幕,显示在屏幕最上方 */
		.bar {
			position:fixed;
			top:0;
			bottom:0
		}
		.bar a {
			padding: 20px;
		}
		div.content div {
			padding-top: 20px;
			height: 1000px;
			scroll-behavior: smooth;
		}
		/* 加上这一句,实现平滑滚动效果 */
		html, body {
			scroll-behavior:smooth;
		}

	</style>
	<body>
		<div class="bar">
			<a href="#div1">跳转1</a>
			<a href="#div2">跳转2</a>
			<a href="#div3">跳转3</a>
		</div>

	<div class="content">
		<div id="div1">这是div1</div>
		<div id="div2">这是div2</div>
		<div id="div3">这是div3</div>
	</div>
	</body>
</html>
<script>

</script>

(2)scrollIntoView跳转

语法:

element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); //布尔参数
element.scrollIntoView(scrollIntoViewOptions); //对象参数

 在vue3中应用(结合上面页面中的案例):

绑定a标签,href地址填入对应id名称,增加点击事件

 <div v-for="(item,index) in navList" :key="index">
            
            <a :href="'#' + index" class="mulu-item" :class="index==navIndex?'active':''"  @click.prevent="clickNav(index,item)" >
                <img :src="item.icon" alt="">
                {{item.title}}
            </a>
        </div>
<div class="link" v-for="(content,index) in navList" :key="content.name">
                <h2 :id="index">{{content.title}}</h2>
               ........
          </div>
const clickNav = (index, item) => {
		navIndex.value = index
    const element = document.getElementById(index);
      element.scrollIntoView({ behavior: 'smooth' });
		
	}

(3)v-scrollspy插件

在 Vue 中,你可以使用 v-scrollspy 指令来设置目录的锚点。首先,你需要安装 vue-scrollspy

import VueScrollspy from 'vue-scrollspy';

在vue组件中使用:

<div class="mulu-item" :class="index==navIndex?'active':''"  @click="clickNav(index,item)" >
                <img :src="item.icon" alt="">
                <a :href="'#' + index">{{item.title}}</a>
            </div>

<div class="link" v-for="(content,index) in navList" :key="content.name">
                <h2 :id="index">{{content.title}}</h2>
               ........
          </div>
import VueScrollspy from 'vue-scrollspy';


methods: {
    clickNav(index, item) {
      this.navIndex = index;
      this.$scrollspy.scrollTo(index);
    }
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值