将时间分割成分钟和秒。

4
我有以下代码,它应该能够实现我需要的功能:
function fromSeconds(seconds, showHours = false) {
    if(showHours) {
        var hours = Math.floor(seconds / 3600),
            seconds = seconds - hours * 3600;
    }
    var minutes = (Math.floor(seconds/60) < 10) ? 
        "0" + Math.floor(seconds/60) : Math.floor(seconds/60);
    var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;

    if(showHours) {
        var timestring = hours + ":" + minutes + ":" + seconds;
    } else {
        var timestring = minutes + ":" + seconds;
    }
    return timestring;
}

问题在于我也有这个:
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function() {
    $('#currentTime').html(video[0].currentTime.toFixed(2));
    $('#remTime').html((video[0].duration - video[0].currentTime).toFixed(2));
    $('#totalTime').html(video[0].duration.toFixed(2));
});

我不知道如何应用第一段代码,使例如currentTime以这种方式显示:分钟:秒

请帮忙吗?

4个回答

1
您可以直接将值传递给函数fromSeconds,例如video[0].currentTime,该函数将返回格式化的字符串。
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
    $('#currentTime').html(fromSeconds(video[0].currentTime));
    $('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
    $('#totalTime').html(fromSeconds(video[0].duration));
});

你的答案也有效,只需简单添加:它向我显示了毫秒。非常感谢。+1 - user4850448

1

通过简单的固定,您可以将其保留为:

演示

function fromSeconds(seconds, showHours) {
    if(showHours) {
        var hours = Math.floor(seconds / 3600),
            seconds = seconds - hours * 3600;
    }
    var minutes = ("0" + Math.floor(seconds/60)).slice(-2);
    var seconds = ("0" + parseInt(seconds%60,10)).slice(-2);

    if(showHours) {
        var timestring = hours + ":" + minutes + ":" + seconds;
    } else {
        var timestring = minutes + ":" + seconds;
    }
    return timestring;
}

var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
    $('#currentTime').html(fromSeconds(video[0].currentTime));
    $('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
    $('#totalTime').html(fromSeconds(video[0].duration));
});

那太完美了。谢谢。 - user4850448

0
 $('#currentTime').html(function(){
     var time=video[0].currentTime.toFixed(2);
     //some conversion needed in-order to convert to required format
     fromSeconds(time,false)//returns time 
 });

谢谢您提供的信息。我也会进行验证。 - user4850448

0
假设currentTime是以秒为单位的时间,您需要将该值传递到您的函数中。 fromSeconds返回所需的文本,因此fromSeconds(mytimevalue)将按要求返回mm:ss
video.bind("timeupdate", function() {
    $('#currentTime').html( fromSeconds(video[0].currentTime) );
    $('#remTime').html( fromSeconds(video[0].duration - video[0].currentTime) );
    $('#totalTime').html( fromSeconds(video[0].duration) );
});

另一个选择是使用JavaScript的Date()对象,它以毫秒为值: var currentTime = new Date(video[0].currentTime * 1000); 然后,您可以使用Date.getMinutes()Date.getSeconds()来查找您的值。
更多细节在这里

谢谢您的回复。我会进行验证。+1 - user4850448

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接