问题
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>
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);
}
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.
回答1:
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>
For Chrome
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>
With jQuery
$(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>
来源:https://stackoverflow.com/questions/8983714/video-and-onloadedmetadata-event