vue锚点定位
锚点定位与平滑滚动反定位支持
代码如下
html
<div style="display: flex;height: 442px;"> <el-tabs v-model="activeTabs" class="zxtabsStyle" tab-position="left" @tab-click="tabshandleClick"> <el-tab-pane label="主要致险情景" name="zxqj"></el-tab-pane> <el-tab-pane label="风险防控基本要求" name="yq"></el-tab-pane> <el-tab-pane label="管理措施" name="glcs"></el-tab-pane> </el-tabs> <div> //要切换滚动的内容区域 <div class="con_tab" ref="content"> <div id="zxqj" class="conBlock">介绍</div> <div id="yq" class="conBlock">课程目录</div> <div id="glcs" class="conBlock">课后福利</div> </div>
js
mounted(){ //1.mounted里面自动监听滚动事件 代码如下 this.$refs.content.onscroll = ()=>{ this.handleScroll(); } }, methods:{ handleScroll () { let scrollTop = this.$refs.content.scrollTop; let blocks = document.querySelectorAll('.conBlock'); blocks.forEach((item, index) => { console.log("blocks",item.id) if (scrollTop >= item.offsetTop) { this.activeTabs = item.id; } }) }, tabshandleClick(data){ console.log("data",data) let index=Number(data.index) let blocks = document.querySelectorAll('.conBlock'); let step = 40;//滚动步长 let currentScrollTop = this.$refs.content.scrollTop; let targetOffsetTop = blocks[index].offsetTop; console.log("currentScrollTop",currentScrollTop); console.log("targetOffsetTop",targetOffsetTop); if(currentScrollTop > targetOffsetTop){ const smoothUp = ()=>{ if(currentScrollTop >= targetOffsetTop){ if (currentScrollTop - targetOffsetTop >= step) { currentScrollTop -= step; setTimeout(smoothUp,1); } else { currentScrollTop = targetOffsetTop-step; } this.$refs.content.scrollTop = currentScrollTop; } }; smoothUp(); }else{ const smoothDown = ()=>{ if (currentScrollTop <= targetOffsetTop) { // 如果和目标相差距离大于等于step 就跳 step if (targetOffsetTop - currentScrollTop >= step) { currentScrollTop += step; setTimeout(smoothDown,1); } else { // 否则直接跳到目标点,防止跳过 currentScrollTop = targetOffsetTop-step; } this.$refs.content.scrollTop = currentScrollTop; } }; smoothDown(); } }, }
锚点定位bug无效和替代方式
在vue项目中,使用锚点定位会和router的规则冲突,在项目中的表现就是第一次点击url改变了,但是没有跳转到锚点位置,再次点击才会跳转。
在vue项目中定义一个方法不适用锚点定位
scrollToSection(id) { let section = document.getElementById(id) if (section) { section.scrollIntoView() } }
html标签中绑定click事件就可以了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持阿兔在线工具。