页面上多个视频的显示时长 [英] Display Duration for Multiple Videos on a Page

查看:215
本文介绍了页面上多个视频的显示时长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示持续时间"使用JavaScript在网页上的每个视频. 到目前为止,这是我要提出的:

I'm trying to display "duration" for each video on the page using JavaScript. here is what I've come up with so far:

var vid = document.querySelector(".mhdividdur");
vid.onloadedmetadata = function() {
  var x = document.querySelector(".mhdividdur").duration;
document.querySelector(".mhdi_video_duration").innerHTML = x;
};

<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>

问题在于它只返回第一个视频的时长.

The problem is that it only returns the duration for the 1st video.

我该怎么办?

P.S.除了JavaScript以外,如果还有其他方法可以显示持续时间,请给我一个提示.

P.S. If there are any other ways except JavaScript to display duration, please give me a hint.

谢谢大家

推荐答案

使用querySelector函数,您可以获得与您输入的选择器匹配的第一个元素.这就是为什么需要使用querySelectorAll函数获取所有视频元素的原因,该函数将返回元素数组并循环打印其持续时间.

with querySelector function you can get the first of the elements that match the selector you entered. that's why you need to get all the video elements with querySelectorAll function which will return an array of elements and loop to print their duration.

var videos = document.querySelectorAll(".mhdividdur");
var durationsEl = document.querySelectorAll(".mhdi_video_duration");
for(let i = 0; i < videos.length; i++) {
  videos[i].onloadedmetadata = function() {
    durationsEl[i].innerHTML = videos[i].duration;
  };
}

<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>

这篇关于页面上多个视频的显示时长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆