锚点滚到导航栏高亮

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>vue锚点滚动</title>
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	</head>
	<body>
		<div id="demo-app" v-cloak>
			<div class="demo-left" ref="demoLeft" @scroll="onScroll">
				<div class="left-box" v-for="(v) in 10" :key="v" ref="contentBox">
					<span>{
   
   {v}}</span>
				</div>
			</div>
			<div class="demo-right">
				<div class="right-nav-box">
					<div class="right-nav" v-for="(v,k) in 10" :key="k" @click="onHandlerClick(k)" :class="{'right-nav-active': active === k}"
					 ref="rightNav">{
   
   {v}}</div>
				</div>
			</div>
		</div>
	</body>

	<script>
		const vm = new Vue({
			el: '#demo-app',
			data() {
				return {
					active: 0,
					activeArr: []
				}
			},
			mounted() {
				this.init()
				window.onresize = () => {
					this.init()
				}
			},
			methods: {
				init() {
					this.$nextTick(() => {
						setTimeout(() => {
							this.activeArr = []
							this.$refs['contentBox'].map(item => {
								item.style.background = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
								this.activeArr.push(item.offsetTop)
							})
						}, 300) // 延时加载,防止拿到的数值不准确
					})
				},
				onHandlerClick(index) {
					this.$refs['demoLeft'].scrollTo({
						top: this.$refs['contentBox'][index].offsetTop,
						behavior: 'smooth'
					})
				},
				onScroll(e) {
					this.activeArr.map((item, index) => {
						if (e.target.scrollTop + 200 >= item) {
							this.active = index
						}
					})
				}
			}
		})
	</script>

	<style>
		[v-cloak] {
			display: none;
		}

		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}

		html,
		body {
			width: 100%;
			height: 100%;
			overflow: hidden;
		}

		#demo-app {
			display: flex;
			width: 100%;
			height: 100%;
		}

		.demo-left {
			flex: 1;
			flex-shrink: 1;
			overflow: auto;
		}

		.left-box {
			width: 100%;
			height: 100%;
			display: flex;
		}

		.left-box span {
			margin: auto;
			font-size: 70px;
		}

		.demo-right {
			flex-basis: 100px;
			display: flex;
			flex-direction: column;
		}

		.right-nav-box {
			margin: auto;
			width: 100%;
		}

		.right-nav {
			border: 1px solid #09F;
			border-bottom: none;
			width: 100%;
			height: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}

		.right-nav:last-child {
			border-bottom: 1px solid #09F;
		}

		.right-nav-active {
			background: #09F;
			color: white;
		}

		.right-nav:hover {
			background: #09F;
			color: white;
		}
	</style>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_57163112/article/details/128904614
今日推荐