实现A-Z滑动检索菜单

我们实现一个A-Z滑动检索菜单,这是一个移动端非常常见的功能,页面效果图如下

在实现代码之前我们先了解下JS滚动事件和滑动事件

scrollTop

  一个元素的scrollTop是这个元素的顶部 到 可视区域顶部的距离,如果元素没有垂直方向的滚动条,那么scrollTop为0

scrollHeight

  这是只读属性,是一个元素内容高度的度量,包括不可视区域

clientHeight

  只读属性,是元素内部高度,包括内边距,但是不包括水平滚动条,边框,外边距

现在我们知道了这三个属性的具体含义,那么我们可以实现滚动页面,A-Z也跟着导航

首先我们通过计算每个A-Z标题的高度listHeight代码如下

const list = this.$refs.listGroup
let height = 0
this.listHeight.push(height)
for (let i = 0; i < list.length; i++) {
  height += list[i].clientHeight
  this.listHeight.push(height)
}

这段代码非常简单,就是通过$refs获得dom元素,也就是A-Z标题,计算每个标题包括上图A字母开头的歌手信息元素的高度分别存储在listHeight中

我们既然获得每个A-Z的元素的高度,那么接下来监听页面滚动

window.addEventListener('scroll', e => {
  const scrollTop = document.documentElement.scrollTop
  for (let index = 0; index < this.listHeight.length; index++) {
    const height = this.listHeight[index]
    const height2 = this.listHeight[index + 1]
    if (index <= this.listHeight.length - 2 && scrollTop >= height - 1 && scrollTop < height2) {
      this.fixedTitle = this.letters[index]
      this.letterIndex = index
    }
  }
})

我们分析这段代码,监听document.documentElement的scrollTop的值,上面介绍了scrollTop的具体含义

好,首先我们scrollTop开始值为0

A-B-C-D......-Z

A元素的高度从listHeight[0]-listHeight[1]之间,为什么这么说,首先listHeight[0]=0是A元素顶部的距离,那么listHeight[1]是A元素的高度,也就是B元素顶部的距离

当我们在listHeight[0]-listH[1]就能判断我们现在滚动的可视区是A元素之内

这样我们就能确定现在是A

这样就能实现滚动页面,能监听A-Z菜单的滚动情况

接下来我们要监听A-Z菜单实现页面滚动到对应标题内容

在代码之前还是先了解下几个js知识

滚动到文档中某个坐标

window.scrollTo(x-coord,y-coord )

window.scrollTo(options)

touch中e.touches[0]中有三个非常关键的属性

pageY 触摸点相对于document上边缘坐标

clientY 触摸点相对于浏览器viewport上边缘的坐标

screenY 触摸点相对于屏幕上边缘的坐标

首先我们要非常清楚这三个属性值。那么我们先弄一段代码

console.log(e.touches[0].pageY, e.touches[0].screenY, e.touches[0].clientY
点击A-Z触发联动
bindClick (index) {
  this._scrollTo(index)
  this.fixedTitle = this.letters[index]
}

_scrollTo (index) {
  // 检测index是否合法
  if (index < 0 || index >= this.listHeight.length) return

  window.scrollTo({
    top: this.listHeight[index],
    bahavior: 'smooth'
  })
  this.letterIndex = index
}
touchMove (e) {
  this.startY2 = e.touches[0].clientY
  const index = parseInt((this.startY2 - this.$refs.letter.offsetTop) / 20)
  this._scrollTo(index)
},

分析下touchMove

首先获得点击到浏览器viewport上边缘的距离,然后获得该元素this.$refs.letter.offsetTop到顶部的距离 。

那么this.startY2 - this.$refs.letter.offsetTop获得的是A-Z菜单滑动到某个位置

这里的20是A-Z单个DIV的高度,然后/20就能获得index

原文地址:https://www.cnblogs.com/sonwrain/p/10703183.html