JavaScript display duration
I'm trying to make a little counter that display how much a movie has played, like on YouTube.
I want the time to output a like this:
<div id="timeInfo">00:23</div>
How do I achieve this? I tried the following without success:
function infTime (){
timeInfo.innerHTML = formatTime(video.currentTime);
if (video.duration) {
timeInfo.innerHTML = formatTime(video.duration);
}
}
function formatTime (seconds) {
seconds = Math.round(seconds);
minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : "0" + min开发者_StackOverflowutes;
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
return minutes + ":" + seconds;
}
This line is problematical:
seconds = Math.round(seconds);
You want to use Math.floor
here to get the correct result.
Live demo: http://jsfiddle.net/simevidas/h6yst/
You're overwriting the content by assigning to "innerHTML" twice. The second expression could be written with "+=", or else (better) you could build the string separately:
infTime: function() {
var info = formatTime(video.currentTime) + (video.duration ? ' ' + formatTime(video.duration) : '');
timeInfo.innerHTML = info;
}
Now, of course that presumes that "timeInfo" is really a reference to the appropriate DOM element, obtained perhaps like this:
var timeInfo = document.getElementById('timeInfo');
Also, do remember to make "minutes" be a local variable by preceding its first use in the "formatTime" function with the var
keyword:
var minutes = Math.floor(seconds / 60);
精彩评论