赞
踩
实现移动端的横向滚动的导航栏,选中的导航项需居中显示
@scroll 滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
<scroll-view class="bg-white nav fixed flex text-center"
:style="[{top:CustomBar1 + 'px'},{paddingLeft: `15px`},{paddingRight:`15px`}]" scroll-x
:scroll-left="scrollLeft" @scroll="scroll">
<view class="cu-item text-sm" :class="item.label===TabCur?'text-black text-bold':''"
v-for="(item,index) in titleList" :key="index" @tap="tabSelect" :data-id="item.label">
{{item.value}}
</view>
</scroll-view>
export default { data() { return { StatusBar: this.StatusBar, CustomBar: this.CustomBar, CustomBar1: 0, scrollLeft: 0, titleList: [{ label: 'all', value: '全部任务' }, { label: 'willExtended', value: '将超期任务' }, { label: 'execute', value: '我执行的任务' }, { label: 'firsttrial', value: '我初审的任务' }, { label: 'recheck', value: '我复审的任务' }, { label: 'all', value: '我创建的任务' }, { label: 'overdue', value: '超期任务' }], left: 0 }; }, methods: { scroll(e) { // 获取滚动条滚动的距离 this.left = e.detail.scrollLeft }, tabSelect(e) { // 当前点击元素的左边距离 const distanceL = e.target.x // 点击元素的一半宽度 const elementHW = document.getElementsByClassName('cu-item text-bold')[0].clientWidth / 2 const screenW = document.body.clientWidth // 屏幕宽度的一半 const screenHW = document.body.clientWidth / 2 // 元素右边距离 const distanceR = screenW - distanceL setTimeout(() => { // 重新计算滚动条滚动的距离 this.initScrollLeft(distanceL, elementHW, screenHW, distanceR) }, 100) }, initScrollLeft(distanceL, elementHW, screenHW, distanceR) { // 当元素左边距离大于屏幕一半宽度 或者 右边距离大于屏幕一半距离的时候 if (distanceL > (screenHW - elementHW) || distanceR > (screenHW - elementHW)) { // 滚动条最终的滚动距离 this.scrollLeft = this.left + (distanceL - screenHW + elementHW) } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。