& lt;视频& gt;和onloaded元数据事件 [英] <video> and onloadedmetadata-event
问题描述
我想在JavaScript中使用HTML5视频元素的尺寸. video
-标记本身没有设置任何尺寸,因此我希望它可以缩放到视频的大小(确实如此).我的标记看起来像这样:
I'd like to use the dimensions of a HTML5 video element in JavaScript. The video
-tag itself does not have any dimensions set, so I expect it to scale to the size of the video (which it does). My markup looks like this:
<video id="viddy" autoplay>
<source src="myvideo.mp4" type='video/mp4; codecs="avc1.42E01E"' />
</video>
当我仅使用jQuery获取元素的height()
和/或width()
时,我将获得默认值300,因为它不会等待视频加载.
因此,我在网上发现的内容(此处和此处)是我应该等待onloadedmetadata
事件.因此,我尝试在JS中执行以下操作:
When I just use jQuery to get the element's height()
and/or width()
I will get a default value of 300 as it will not wait for the video to load.
So what I found out on the web (here and here) is that I should be waiting for the onloadedmetadata
-event. So I am trying to do the following in my JS:
var video = document.getElementById('viddy');
video.onloadedmetadata = function(e){
var dimensions = [video.videoWidth, video.videoHeight];
alert(dimensions);
}
但是,该事件将永远不会触发(尽管视频会加载和播放),而且我永远也无法掌握尺寸. jQuery- bind('load',
和其他我能想到的方式也是如此.任何的想法?谢谢.
Yet, the event will never fire (although the video will load and play) and I'll never get my dimensions. Same happens with a jQuery-bind('load',
and every other way I could think of. Any idea? Thanks.
推荐答案
将代码放入HTML头末尾的function
中(例如称为init
),并将其绑定到DOMContentLoaded
事件:
Put your code into a function
at the end of your HTML head (e.g. called init
) and bind it to the DOMContentLoaded
event:
function init() {
var video = document.getElementById('viddy');
video.onloadedmetadata = function(e){
var dimensions = [video.videoWidth, video.videoHeight];
alert(dimensions);
}
}
document.addEventListener("DOMContentLoaded", init, false);
<video id="viddy" autoplay>
<source src="http://media.w3.org/2010/05/sintel/trailer.webm" type='video/webm' />
</video>
您应该更改将侦听器添加到:
You should change adding the listener to:
video.addEventListener('loadedmetadata', function(e){
function init() {
var video = document.getElementById('viddy');
video.addEventListener('loadedmetadata', function(e){
var dimensions = [video.videoWidth, video.videoHeight];
alert(dimensions);
});
}
document.addEventListener("DOMContentLoaded", init, false);
<video id="viddy" autoplay>
<source src="http://media.w3.org/2010/05/sintel/trailer.webm" type='video/webm' />
</video>
$(document).ready(function() {
$('#viddy').on('loadedmetadata', function() {
var dimensions = [this.videoWidth, this.videoHeight];
alert(dimensions);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<video id="viddy" autoplay>
<source src="http://media.w3.org/2010/05/sintel/trailer.webm" type='video/webm' />
</video>
这篇关于& lt;视频& gt;和onloaded元数据事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!