我在同一页上加载多个视频(在旋转木马中),对于每个单独的视频,我想设置视频的持续时间。下面的代码显示了两个示例,一个尝试使用jQuery .each()
使其对每个视频有效,另一个有效,但仅适用于第一个视频,随后它对每个视频应用相同的持续时间。
如何让jQuery逐个遍历视频?
谢谢!
Each (不工作)
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>
发布于 2018-06-10 04:41:32
第一种方法不起作用的原因是您将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");
});
});
即使这样,您的设置也只有一个持续时间显示,因此它将显示要加载的最后一个视频的持续时间
https://stackoverflow.com/questions/50764643
复制相似问题