<div class="progress-wrapper">
<span class="time time-l">{{ format(currentTime) }}</span>
<div class="progress-bar-wrapper">
<progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
</div>
<span class="time time-r">{{ format(currentSong.duration) }}</span>
</div>
<audio :src="currentSong.url" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
updateTime(e){
this.currentTime = e.target.currentTime; // 获取当前播放时间段
},
format(interval){
interval = interval | 0;
const minute = interval/60 | 0;
const second = this._pad(interval % 60);
return `${minute}:${second}`;
},
_pad(num,n=2){
let len = num.toString().length;
while(len<n){
num = '0' + num;
len ++;
}
return num;
},
建立progress-bar 组件 接收pencent 进度参数,设置进度条宽度和小球的位置。player组件 设置计算属性percent
percent(){
return this.currentTime / this.currentSong.duration // 当前时长除以总时长
},
progress-bar 组件
<div class="progress-bar" ref="progressBar" @click="progressClick"> <div class="bar-inner"> <div class="progress" ref="progress"></div> <div class="progress-btn-wrapper" ref="progressBtn" @touchstart.prevent="progressTouchStart" @touchmove.prevent="progressTouchMove" @touchend="progressTouchEnd" > <div class="progress-btn"></div> </div> </div> </div>
const progressBtnWidth = 16 //小球宽度
props:{
percent:{
type:Number,
default:0
}
},
watch:{
percent(newPercent){
if(newPercent>=0 && !this.touch.initated){
const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth;
const offsetWidth = newPercent * barWidth;
this.$refs.progress.style.width = `${offsetWidth}px`;
this.$refs.progressBtn.style.transform=`translate3d(${offsetWidth}px,0,0)`
}
}
}
设置拖动
在进度条小按钮progressBtn 上添加touchstart,touchmove,touchend 事件监听方法,事件添加 prevent 防止拖动默认浏览器行为,获取拖动的信息进行计算
在实例上创建一个touch 对象维护不同的回调之间的通讯共享状态信息。 touchstart事件方法中 ,首先设置this.touch.initated为true,表示拖动开始。 记录开始点击位置 e.touches[0].pageX 存到 touch 对象上,记录当前的进度宽度。
在touchmove 中首先判断 是否先进入了 touchstart 方法,计算得到 移动的位置 减去 点击开始的位置的 偏移量长度。 let deltax = e.touches[0].pageX - this.touch.startX
