在同一页面上设置多个视频的持续时间

时间:2018-06-08 16:12:41

标签: jquery html5 video html5-video

我在同一页面上(在旋转木马内)加载多个视频,并且对于每个单独的视频,我想设置视频的持续时间。下面的代码显示了两个示例,一个尝试使用jQuery .each()使其适用于每个视频,另一个可用,但仅适用于第一个视频,随后它会对每个视频应用相同的持续时间。

如何让jQuery逐个循环播放视频?

谢谢!

每个(不起作用)

var video = document.getElementById('video');

// Set video duration in caption
video.each(function () {
    this.addEventListener('loadedmetadata', function() {
        // vars
        var total = video.duration.toFixed(0); // Total number of seconds with 0 decimal places
        var minutes = Math.floor(total / 60); // Seconds divided by 60 to get total minutes
        var seconds = total % 60; // Seconds remaining once minutes are removed

        $('.duration .time').text(minutes + ":" + seconds + "s");
    });
});

个人(有效但对所有视频应用相同的持续时间)

var video = document.getElementById('video');

// Set video duration in caption
video.addEventListener('loadedmetadata', function() {
    // vars
    var total = video.duration.toFixed(0); // Total number of seconds with 0 decimal places
    var minutes = Math.floor(total / 60); // Seconds divided by 60 to get total minutes
    var seconds = total % 60; // Seconds remaining once minutes are removed

    $('.duration .time').text(minutes + ":" + seconds + "s");
});

HTML

<div class="video-wrapper">
    <video id="video" src="URL" poster="POSTER URL" preload></video>
</div>

<div class="meta">
    <h5 class="duration"><span class="time"></span></h5>
</div>

1 个答案:

答案 0 :(得分:0)

第一个不起作用的原因是因为你将each应用于单个元素,加上语法错误

假设您的设置实际上有多个视频标签,这将是一种更好的方法

var videos = $('video');

videos.each(function () {
    $(this).on('loadedmetadata', function(e) {
        // vars

        var total = e.target.duration.toFixed(0); // Total number of seconds with 0 decimal places
        var minutes = Math.floor(total / 60); // Seconds divided by 60 to get total minutes
        var seconds = total % 60; // Seconds remaining once minutes are removed

        $('.duration .time').text(minutes + ":" + seconds + "s");
    });
});

即便如此,您的设置只有一个持续时间显示,因此它会显示上一个要加载的视频的持续时间