vue-music:歌词和cd切换

**在播放器CD的界面,向左划动则会出现歌词,在歌词界面,向右滑动则会初心CD界面
下面是实现这个功能的相关逻辑代码:**

  1. 移动端touch事件
  2. 定义公共数据this.touch
  3. 移动transform translate3d 动画transitonDuration

1.touch定义事件和数据

《vue-music:歌词和cd切换》
同时:data中定义this.currentShow:’cd’; 在created中定义this.touch = {}
原因:只是touch几个方法中共享这个数据,不用数据绑定,因此在created钩子中定义

2.开始滑动touchStart

  • 记录x,y坐标
  • 加个flag,initiated:true开始滑动,则继续move
middleTouchStart(e) {
   this.touch.initiated = true
   this.touch.startX = e.touches[0].pageX
   this.touch.startY = e.touches[0].pageY
}, 

3.滑动中touchMove

获取dom:

  • 组件$refs[名称]$el.style:lyricList是一个scroll组件,是一个vue组件,通过$el可以获取dom
  • 非组件直接$refs[名称].style

临界值:

  • 0
  • -window.innerWidth
middleTouchMove(e) {
      //move的一个标志位,开始滑动
      if (!this.touch.initiated) {
        return
      }
      //从右→往左滑动,deltaX是负数
      //从左→往右滑动,deltaX是正数
      const deltaX = e.touches[0].pageX - this.touch.startX
      const deltaY = e.touches[0].pageY - this.touch.startY
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        //当纵轴大于横轴的偏移的时候,就不应该移动,这里是横向移动
        return
      }
     
      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      
      //this.currentShow === 'cd'  0  从右→往左滑动,deltaX是负数,0 + deltaX大
      //this.currentShow === 'lyric'  -window.innerWidth  从左→往右滑动,deltaX是正数  -window.innerWidth + deltaX  大
      
      //临界值
      const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      
      //percent是给opacity,控制透明度,实现渐入渐出效果
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      
      //获取dom:组件$el;非组件直接ref名称.style
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px, 0, 0)`
      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = 0
 },

4.滑动结束

这里有个临界值,什么时候开始直接滑动结束
this.touch.percent:0.1和0.9

middleTouchEnd(e) {
    let offsetWidth
    let opacity
    //右 → 左滑动
    if (this.currentShow === 'cd') {
        //percent临界值0.1  0.9
        if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth
            opacity = 0
            this.currentShow = 'lyric'
        } else {
            offsetWidth = 0
            opacity = 1
        }
    } else {
        左 → 右滑动
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
    }
    const durationTime = 300
    this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px, 0, 0)`
    
    // 过渡的时间,在move的时候要清零
    this.$refs.lyricList.$el.style[transitionDuration] = `${durationTime}ms`
    this.$refs.middleL.style[transitionDuration] = `${durationTime}ms`
    
    this.$refs.middleL.style.opacity = opacity
}
    原文作者:云深不知处
    原文地址: https://segmentfault.com/a/1190000016692498
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞