最近做到一个项目,突然需要一个这样的效果,导航栏过长的时候,切换的目标要居中,使得用户体验感更加有好
代码结构
<ul class="mobile-nav-list"
ref="navList">
<li :class="currentActiveLi === 1 ? 'active' : '' "
@click="switchNavType($event, 1)">
全部视频
</li>
<li :class="currentActiveLi === 2 ? 'active' : '' "
@click="switchNavType($event, 2)">
寿险科普
</li>
<li :class="currentActiveLi === 3 ? 'active' : '' "
@click="switchNavType($event, 3)">
产品发布
</li>
<li :class="currentActiveLi === 4 ? 'active' : '' "
@click="switchNavType($event, 4 )">
财新私房课
</li>
<span ref="bottomSlider"> </span>
</ul>
实现过程
switchNavType (el, index) {
this.currentActiveLi = index
let target = el ? el.target : this.$refs.navList.childNodes[0]
let currentSliderWidth = target.clientWidth / 2
setTimeout(() => {
this.$refs.bottomSlider.style.left = target.offsetLeft + currentSliderWidth + 'px'
}, 50)
this.$refs.bottomSlider.style.width = (target.clientWidth - 50) + 'px'
// 航条切换居中实现
// let offsetLeft = target.offsetLeft
let dom = this.$refs.navList
let innerWidth = window.innerWidth // 屏幕宽度
let diffWidth = (innerWidth - target.clientWidth) / 2
let targetOffset = target.offsetLeft - diffWidth
if (targetOffset < 0) {
this.$refs.navList.scrollLeft = 0
dom.scrollIntoView(true)
return
}
this.$refs.navList.scrollLeft = targetOffset
}
感觉有点不完美,就是滑动的时候有点闪动😭