一个简单的静态页面主要是使用 better-scroll 作横向滚动,
点击标签滚动到相应位置,以及滚到相应位置后对应标签显示红色。
开发过程当中遇到了几个问题
一:初始化的时候要计算内容的高度,一直有偏差,由于一开始直接用img引入的,没加载完就计算高度就会有问题
解决办法:用background写图片,而后高度写死
二:滚动到某个内容,对应标签高亮
这里比较的是当前滚动位置高度和内容距离dom顶部的高度加上实际nav的高度
三:better-scroll fixed后滚动失效
这里是由于没有给固定的宽度,用了100%形成的。这里给了tab-warp 宽度就解决了git
记录一下和你们共同窗习github
由于是静态野蛮标题放到数组中了小程序
itemList: [{ 'title': '战略升级' }, { 'title': '官方受权' }, { 'title': '100%正品' }, { 'title': '全链路监管' }, { 'title': '阳光保险' }, { 'title': '售后无忧' }, { 'title': '专业仓储' }, { 'title': '用户好评' }, { 'title': '媒体监督' }, { 'title': '资质公示' } ], mounted() { this.$nextTick(() => { window.addEventListener('scroll', this.handleScroll) // 监听滚动事件 this.InitTabScroll() // 初始化滚动 }) }, methods: { handleChange(index) { this.swipeIndex.nowIndex = index + 1 }, // 监听滚动事件 handleScroll() { const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 吸顶效果 const isFixed = scrollTop >= this.tabToTop if (isFixed !== this.isFixed) { this.isFixed = isFixed } // 当页面滚动时候标签也要滚动 for (var i = 0; i < this.contentH.length; i++) { // 循环判断内容高度的数组,滚动的高度小于前一个大于后一个设置,这里是包含下拉面板的高度(我也不知道为何,本身试出来的,尴尬) if (scrollTop + this.tabRealHeight> this.contentH[i] && scrollTop + this.tabRealHeight< this.contentH[i + 1]) { if (this.checkIndex !== i) { this.checkIndex = i // 而后设置标签高亮,滚动到居中位置 this.scroll.scrollToElement(this.$refs.tabitem[i], 300, -100) } } } }, // 初始化方法 InitTabScroll() { /* * 这里有几个高度须要注意一下,由于后面要计算滚动距离,这里要很精确要不就会出问题 * tabToTop tab距离顶部的高度,也就是第一个图片的高度 * tabRealHeight 是tab点下拉箭头显示面板后的高度 * tabHeight 就是tab的高度了 */ // 头部高度 this.tabToTop = this.$refs['tab-containter'].offsetTop // tab 带面板高度 this.tabRealHeight = this.$refs['tab-containter'].offsetHeight // tab 高度 this.tabHeight = this.$refs['tabitem'][0].offsetHeight // 内容高度要记录下来放在数组里,当页面滚动的时候判断在哪一个区间,对于标签高亮 for (let i = 0; i < 11; i++) { this.contentH.push(this.$refs['contentItem' + i].offsetTop) } // nav横向滚动宽度,而后设置 let width = 0 for (let i = 0; i < this.itemList.length; i++) { width += this.$refs.tabitem[i].getBoundingClientRect().width // getBoundingClientRect() 返回元素的大小及其相对于视口的位置 } this.$refs.tabWrapper.style.width = width + 'px' this.$nextTick(() => { if (!this.scroll) { this.scroll = new BScroll(this.$refs.tab, { startX: 0, click: true, scrollX: true, scrollY: false, eventPassthrough: 'vertical' }) } else { this.scroll.refresh() } }) }, // 点击nav标签 checkStatus(index, pop) { this.checkIndex = index // 点击展开面板的选项 if (pop) { this.flag = !this.flag } // 点击标签后,标签要滚到nav中间位置 this.scroll.scrollToElement(this.$refs.tabitem[index], 300, -100) // 获取该点击标签对应的内容区域,距离dom顶部高度 const offsetTop = this.$refs['contentItem' + index].offsetTop // 页面滚动到高度减去nav的位置 window.scrollTo(0, offsetTop - this.tabHeight) } }
主要功能实现了,可是还有不少须要优化的地方
查看demo 正品保障 完整代码 github
微信扫码看咱们的小程序数组
您能够扫描添加下方的微信并备注 Soul 加交流群,给我提意见,交流学习。微信