<div class="audio">
<audio id="audio" ref="audio" src="http://www.w3school.com.cn/i/horse.ogg"></audio>
<div class="stopbtn" @click="play" v-if="flag"></div>
<div class="playbtn" @click="paused" v-else></div>
<div class="timebar" ref="timebare" @touchmove="timebarmove($event)" @click="clickbar($event)">
<div class="bar" ref="bar" @touchstart="touchstart($event)">
<span></span>
</div>
<div class="mask" ref="mask"></div>
</div>
<div class="time">{{ currentTime }} / {{ alltime }}</div>
</div>
data () {
return {
currentTime: 0,
statu: false,
ox: 0,
left: 0,
alltime: '',
state: false,
flag: true
}
},
mounted () {
var audio = document.getElementById('audio')
audio.addEventListener('canplay', () => {
this.alltime = audio.duration//获取总时长
})
},
methods: {
play () {
this.flag = false
let timer = setInterval(() => {
this.currentTime += 1
if (this.currentTime > this.alltime) {
clearInterval(timer)
this.currentTime = this.alltime
this.flag = true
this.currentTime = 0
}
this.$refs.bar.style.cssText = 'left:' + this.currentTime / this.alltime * 213 + 'px'
this.$refs.mask.style.cssText = 'width:' + this.currentTime / this.alltime * 213 + 'px'
}, 1000)
},
paused () {
this.flag = false
},
touchstart (e) {
this.ox = e.touches[0].pageX - this.left
this.statu = true
},
timebarmove (e) {
if (this.statu) {
this.left = e.touches[0].pageX - Number(this.ox)
if (this.left < 0) {
this.left = 0
}
if (this.left > 213) {
this.left = 213
}
this.$refs.bar.style.cssText = 'left:' + this.currentTime / this.alltime * 213 + 'px'
this.$refs.mask.style.cssText = 'width:' + this.currentTime / this.alltime * 213 + 'px'
}
},
clickbar (e) {
if (!this.statu) {
this.left = e.x - 82
if (this.left < 0) {
this.left = 0
}
if (this.left > 213) {
this.left = 213
}
this.$refs.bar.style.cssText = 'left:' + this.currentTime / this.alltime * 213 + 'px'
this.$refs.mask.style.cssText = 'width:' + this.currentTime / this.alltime * 213 + 'px'
}
},
touchend () {
this.statu = false
}
}