vue中使用锚点(x轴y轴)
需求1:点击左侧导航栏,页面需要滚动到对应的标题。(y轴)
第一步:给中间内容div从第一个开始每一个最外层盒子添加一个class||id一个标识。(不能相同)
第二步:使用 window.scrollTo(支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant)
window.scrollTo({
top: distance, //滚动高度
behavior: 'smooth'
})
完整代码:
<div class="left-common line1" :class="lefTabIndex==index?'cor6356FF':isBuy?'item':''"
v-for="(item,index) in dingweiList" @click="goDingyue(index)">
{{ item }}
</div>
dingweiList: ['1.基本概念', '2.研究趋势', '3.相关概念', '4.相关维度推荐', '5.相关理论推荐', '6.相关方法推荐', '7.限定词推荐', '8.核心参考文献', '9.主题文献综述推荐', '10.核心参考著作', '11.立项课题推荐', '12.相关学习视频推荐']
goDingyue (index) {
if (this.isBuy) {
this.lefTabIndex = index
let distance = this.$el.querySelector('.dingwei' + (index + 1)).offsetTop - 150 //获取div距离顶部的距离减去导航条的高度
window.scrollTo({
top: distance,
behavior: 'smooth'
})
}
},
需求2:点击上面的标题,x轴滑动
第一步:给下面内容的div从第一个开始每一个最外层盒子添加一个class||id一个标识。(不能相同)
第二步:使用 scrollIntoView(支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant)
document.getElementById(id).scrollIntoView({ behavior: 'smooth' })
完整代码:
<div class="hot-subject">
<div class="hot-subject-item" v-for="(item,index) in keys" @click="rollHead(index)">{{ item.album }}</div>
</div>
rollHead (index) {
let id = 'go' + (index + 1)
document.getElementById(id).scrollIntoView({ behavior: 'smooth' })
},