Progress_bar为歌曲
我需要一个跟随歌曲时间的进度条。 如何在歌曲结束时准确设置progress_bar的结束时间?
恩。 如果我的歌曲持续时间为4:38分钟,我怎么能在这个特定的时间段内创建一个progress_bar(从我点击到4:38分钟后)?
var progressBar = $('#progress-bar'), width = 0; progressBar.width(width); var interval = setInterval(function() { width += 10; progressBar.css('width', width + '%'); if (width >= 100) { clearInterval(interval); } }, 1000)
谢谢。
4:38是4 * 60 + 38 = 278秒,这意味着每秒钟应该移动(1/278)* 100%
var step = 100/(minutes*60 + seconds); var interval = setInterval(function() { width += step; progressBar.css('width', width + '%'); if (width >= 100) { clearInterval(interval); } }, 1000)
这是我通常做的事情:
var player = new Audio('http://goo.gl/mGVqyF'); player.play(); var winWidth = window.innerWidth; var timer = setInterval(function(){ document.getElementById('timebar').style.width = player.currentTime / player.duration * winWidth +'px'; },100); // stop the setInterval when song ended player.addEventListener('ended',function(){ clearInterval(timer); });
它不会猜测它何时结束,它会从当前duration
和duration
的玩家那里获取此信息。
JS小提琴演示
使用相关的HTML5媒体事件,如timeupdate
和ended
。 您可以在http://www.w3.org/2010/05/video/mediaevents.html上看到它们的运行情况
关于你的代码,它就像
var progressBar = $('#progress-bar'), width = 0; progressBar.width(width); $(audio).on('timeupdate',function(e){ var progress = this.currentTime / this.duration; progressBar.css('width', progress*100+'%'); });
您可能不使用HTML5媒体。 所以,无论如何我不建议在这种情况下使用setInterval
。 使用类似于上面显示的方式。