vue中的锚点定位
vue锚点定位平滑滚动
·
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();
}
},
}
更多推荐
已为社区贡献12条内容
所有评论(0)