vue2.0实现音乐/视频播放进度条组件

2020-06-14 06:03:31易采站长站整理

// 设置偏移值
const offsetWidth = Math.min(Math.max(0, this.touchInfo.left + moveX),
this.$refs.progressBar.clientWidth - this.btnWidth)
this._setOffset(offsetWidth)
},
// 移动结束
progressTouchEnd(e) {
this.touchInfo.initiated = false
// 向父组件派发事件,传递当前百分比值
this._triggerPercent()
},
// 进度条点击事件
progressClick(e) {
console.log('clikc')
// 设置进度条及按钮偏移
this._setOffset(e.offsetX)
// 通知父组件播放进度变化
this._triggerPercent()
},
_triggerPercent() {
const barWidth = this.$refs.progressBar.clientWidth - this.btnWidth
const percent = Math.min(1, this.$refs.progress.clientWidth / barWidth)
this.$emit('percentChange', percent)
},
// 设置偏移
_setOffset(offsetWidth) {
// 设置进度长度随着百分比变化
this.$refs.progress.style.width = `${offsetWidth}px`
// 设置按钮随着百分比偏移
this.$refs.progressBtn.style.transform = `translate3d(${offsetWidth}px, 0, 0)`
}
},
watch: {
// 监听歌曲播放百分比变化
percent(newPercent, oldPercent) {
if (newPercent > 0 && !this.touchInfo.initiated) {
// 进度条总长度
const barWidth = this.$refs.progressBar.clientWidth - this.btnWidth
const offsetWidth = barWidth * newPercent
// 设置进度条及按钮偏移
this._setOffset(offsetWidth)
}
}
}
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
@import "~common/stylus/variable.styl"

.progress-bar
height 0.5rem
.bar-inner
position relative
top 0.2rem
height 0.08rem
background rgba(0, 0, 0, 0.3)
.progress
position absolute
height 100%
background $color-theme
.progress-btn-wrapper
position absolute
left -0.25rem
top -0.25rem
width 0.5rem
height 0.5rem
.progress-btn
position relative
top 0.12rem
left 0.12rem
box-sizing border-box
width 0.32rem
height 0.32rem
border 0.06rem solid $color-text
border-radius 50%
background $color-theme
</style>

此为progerss-bar.vue组件源码,组件所需要父组件传入的值只有一个“percent”,为父组件中audio当前播放时间与总时间的比值,用于计算此组件中橙色进度条的长度。

组件的使用:

首先导入并注册组件(在此不做解释),随后使用此组件,dom:


<div class="progress-wrapper">
<span class="time time-l">{{formatTime(currentTime)}}</span>
<div class="progress-bar-wrapper">