scroll 实现移动端字母索引导航功能(2)

我们需要 better-scroll 的 on 方法,返回内容滚动时候的 Y轴偏移值。所以在初始化 better-scroll 的时候需要添加一下代码。对了,别忘了在 data 中添加一个 scrollY,和 currentIndex (用来记录高亮索引的位置)因为我们需要监听,所以在 data 中添加。

_initSrcoll () { this.scroll = new BScroll(this.$refs.listView, { probeType: 3, click: true }) // 监听Y轴偏移的值 this.scroll.on('scroll', (pos) => { this.scrollY = pos.y }) }

然后需要计算一下内容的高度,添加一个 calculateHeight() 方法,用来计算索引内容的高度。

_calculateHeight () { this.listHeight = [] const list = this.$refs.listGroup let height = 0 this.listHeight.push(height) for (let i = 0; i < list.length; i++) { let item = list[i] height += item.clientHeight this.listHeight.push(height) } } // [0, 760, 1380, 1720, 2340, 2680, 2880, 3220, 3420, 3620, 3960, 4090, 4920, 5190, 5320, 5590, 5790, 5990, 6470, 7090, 7500, 7910, 8110, 8870] // 得到这样的值

然后在 watch 中监听 scrollY,看代码:

watch: { scrollY (newVal) { // 向下滑动的时候 newVal 是一个负数,所以当 newVal > 0 时,currentIndex 直接为 0 if (newVal > 0) { this.currentIndex = 0 return } // 计算 currentIndex 的值 for (let i = 0; i < this.listHeight.length - 1; i++) { let height1 = this.listHeight[i] let height2 = this.listHeight[i + 1] if (-newVal >= height1 && -newVal < height2) { this.currentIndex = i return } } // 当超 -newVal > 最后一个高度的时候 // 因为 this.listHeight 有头尾,所以需要 - 2 this.currentIndex = this.listHeight.length - 2 } }

得到 currentIndex 的之后,在 html 中使用。

给索引绑定 class -->  :class="{'current': currentIndex === index}"

最后再处理一下滑动索引的时候改变 currentIndex。

因为代码可以重复利用,且需要处理边界情况,所以就把

this.scroll.scrollToElement(this.$refs.listGroup[index])

重新写了个函数,来减少代码量。

// 在 scrollToElement 的时候,改变 scrollY,因为有 watch 所以就会计算出 currentIndex scrollToElement (index) { // 处理边界情况 // 因为 index 通过滑动距离计算出来的 // 所以向上滑超过索引框框的时候就会 < 0,向上就会超过最大值 if (index < 0) { return } else if (index > this.listHeight.length - 2) { index = this.listHeight.length - 2 } // listHeight 是正的, 所以加个 - this.scrollY = -this.listHeight[index] this.scroll.scrollToElement(this.$refs.listGroup[index]) }

lazyload

lazyload 插件也顺便说一下哈,增加一下用户体验。

使用方法

先 npm 安装

在 main.js 中 import,然后 Vue.use

import VueLazyload from 'vue-lazyload' Vue.use(VueLazyload, { loading: require('./common/image/default.jpg') })

添加一张 loading 图片,使用 webpack 的 require 获取图片。

然后在需要使用的时候,把 :src="" 换成 v-lazy="" 就实现了图片懒加载的功能。

总结

移动端字母索引导航就这么实现啦,感觉还是很有难度的哈(对我来说)。

主要就是使用了 better-scroll 的 on 获取移动偏移值(实现高亮)、scrollToElement 跳转到相应的位置(实现跳转)。以及使用 touch 事件监听触摸,来获取开始的位置,以及滑动距离(计算最后的位置)。

总结

以上所述是小编给大家介绍的Vue + better-scroll 实现移动端字母索引导航功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8a9a96f42b4e96cfb53bcf2ceca6de60.html