//定义变量
var playcurrentTime = 0;
var start = "00:00";
var end = "00:00";
var t1;
var pp = 1;
var audio = document.getElementById("player");
var starts = document.getElementById('start');
starts.innerHTML = start;
var ends = document.getElementById('end');
ends.innerHTML = end;
//这里是一些移动端拖动的处理
$(document).ready(function() {
const progressWrapper = document.querySelector('.progress-wrapper')
const progress = document.querySelector('.progress')
const progressBtn = document.querySelector('.progress-btn')
const progressWrapperWidth = progressWrapper.offsetWidth
let touchPoint = 0;
let btnLeft = 0
progressBtn.addEventListener('touchstart', e => {
let touch = e.touches[0]
touchPoint = touch.clientX // 获取触摸的初始位置
btnLeft = parseInt(getComputedStyle(progressBtn, null)['left'], 10) // 此处忽略IE浏览器兼容性
})
progressBtn.addEventListener('touchmove', e => {
e.preventDefault()
window.clearInterval(t1);
pp=2;
plays();
let touch = e.touches[0]
let diffX = touch.clientX - touchPoint // 通过当前位置与初始位置之差计算改变的距离
let btnLeftStyle = btnLeft + diffX // 为按钮定义新的left值
if(btnLeftStyle > progressWrapperWidth) {
btnLeftStyle = progressWrapperWidth
} else if(btnLeftStyle < 0) {
btnLeftStyle = 0
}
var cd = btnLeftStyle;
if(cd < 10) {
cd = 10;
}
touch.target.style.left = cd + 'px'
playcurrentTime = cd;
progress.style.width = (btnLeftStyle / progressWrapperWidth) * 100 + '%' // 通过按钮的left值与进度条容器长度的比值,计算进度条的长度百分比
console.log((btnLeftStyle / progressWrapperWidth) * 100)
})
progressBtn.addEventListener('touchend', e => {
e.preventDefault()
var div = document.getElementById('progress-wrapper');
var width = div.style.width || div.clientWidth || div.offsetWidth || div.scrollWidth; width
audio.currentTime = (playcurrentTime/width) * audio.duration;
pp=1;
plays();
})
});
//处理播放时间
function formatTime(second) {
return [ parseInt(second / 60 % 60), parseInt(second % 60) ].join(
":").replace(/b(d)b/g, "0$1");
}
//播放
function plays() {
if (pp == 1) {
if (audio.paused) {
audio.play();
}
t1 = window.setInterval(function() {
const progress = document.querySelector('.progress');
progress.style.width =(audio.currentTime / audio.duration)* 100 + '%';
starts.innerHTML = formatTime(parseInt(audio.currentTime));
ends.innerHTML = formatTime(parseInt(audio.duration));
var div = document.getElementById('progress-wrapper');
var width = div.style.width || div.clientWidth || div.offsetWidth || div.scrollWidth; width
const progressBtn = document.querySelector('.progress-btn')
progressBtn.style.left =(audio.currentTime / audio.duration)*width + 'px';
}, 200);
pp = 2;
} else {
audio.pause();
window.clearInterval(t1);
pp = 1;
}