<video> and onloadedmetadata-event

前端 未结 2 1296
迷失自我
迷失自我 2021-02-06 12:57

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 o

2条回答
  •  自闭症患者
    2021-02-06 13:31

    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);

    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);

    With jQuery

    $(document).ready(function() {
        $('#viddy').on('loadedmetadata', function() {
            var dimensions = [this.videoWidth, this.videoHeight];
            alert(dimensions);
        });
    });
    
    

提交回复
热议问题