How would you add an onclick event to this audio timeline that goes to the position of audio relative to where you click.
jsfiddle: https://jsfiddle.net/jeffd/6bm3jcfm/1/
HTML:
<audio src="https://99centbeats.com/1e4cb5f584d055a0992385c1b2155786/44ec3770dad9ca5669c4e32439c4c9a1/sick-n-tired-w-vocals-f0fb72ae83.mp3" id="player"></audio>
<button id="play">Play</button>
<button id="pause">Pause</button>
<div class="hp_slide">
<div class="hp_range"></div>
</div>
Jquery:
$('#play').on('click', function() {
document.getElementById('player').play();
});
$('#pause').on('click', function() {
document.getElementById('player').pause();
});
var player = document.getElementById('player');
player.addEventListener("timeupdate", function() {
var currentTime = player.currentTime;
var duration = player.duration;
$('.hp_range').stop(true,true).animate({'width':(currentTime +.25)/duration*100+'%'},250,'linear');
});
CSS
.hp_slide{
width:100%;
height:5px;
background:red;
}
.hp_range{
width:0;
background:black;
height:5px;
}
答案 0 :(得分:3)
The simplest method would be to get the offsetX
of the click within the tracking bar and work that out as a percentage of the total width.
Then you can take that percentage and multiply the duration of the audio by it to set the currentTime
property of the audio element. Something like this:
var player = document.getElementById('player');
var duration = 0;
player.addEventListener("timeupdate", function() {
var currentTime = player.currentTime;
duration = player.duration;
$('.hp_range').stop(true, true).animate({
'width': (currentTime + .25) / duration * 100 + '%'
}, 250, 'linear');
});
$('.hp_slide').click(function(e) {
var pc = e.offsetX / $(this).width();
player.currentTime = duration * pc;
})