2017-02-24 82 views
3

我试过了在这里找到的几个答案。使用JavaScript获取HTML5视频的宽度和高度?

此代码适用于Firefox并输出正确的大小,但不适用于Chrome或IE。

主要是我试图得到宽度。

我有输出用3个例子的视频下方的宽度。

https://jsfiddle.net/a8a1o8k2/

的JavaScript

https://stackoverflow.com/a/4129189/6806643

var vid1 = document.getElementById("video"); 
vid1.videoHeight; // returns the intrinsic height of the video 
vid1.videoWidth; // returns the intrinsic width of the video 

返回0

https://stackoverflow.com/a/9333276/6806643

var vid2 = document.getElementById("video"); 
vid2.addEventListener("loadedmetadata", function (e) { 
    var width = this.videoWidth, 
     height = this.videoHeight; 
}, false); 

返回0

https://stackoverflow.com/a/16461041/6806643

var vid3 = document.getElementById("video"); 
var videotag_width = vid3.offsetWidth; 
var videotag_height = vid3.offsetHeight; 

有时返回正确的值
有时会返回300(默认播放器的大小,如果没有视频源)

回答

1

编辑:改进的方案后,我确实阅读了跨浏览器的问题。

以下解决方案适用于Chrome和Firefox。问题在于Firefox不像Chrome那样对待readyState。

var vid2 = document.getElementById("video"); 
vid2.addEventListener("loadedmetadata", getmetadata); 

if (vid2.readyState >= 2) { 
    getmetadata(vid2); 
} 

function getmetadata(){ 
    document.getElementById('output2').innerHTML = "Test 2: " + vid2.videoWidth; 
} 

更新JSFiddle

+0

你可以显示它在jsfiddle中返回值吗?我没有正确使用文档写入输出。 –

+0

是的,它确实显示**测试2:640 ** – nbo

+0

它在Chrome中显示测试2:640,但在Firefox中显示为空白。 –

0

如果你想定义的大小你视频与Java脚本im不知道你实际上正在做什么,虽然在我看来,你只是希望它可以像这个例子一样定制。

如果我们假定视频嵌入下面的代码可能做的伎俩

// Find all YouTube videos 
var $allVideos = $("iframe[src^='//www.youtube.com']"), 

    // The element that is fluid width 
    $fluidEl = $("body"); 

// Figure out and save aspect ratio for each video 
$allVideos.each(function() { 

    $(this) 
    .data('aspectRatio', this.height/this.width) 

    // and remove the hard coded width/height 
    .removeAttr('height') 
    .removeAttr('width'); 

}); 

// When the window is resized 
$(window).resize(function() { 

    var newWidth = $fluidEl.width(); 

    // Resize all videos according to their own aspect ratio 
    $allVideos.each(function() { 

    var $el = $(this); 
    $el 
     .width(newWidth) 
     .height(newWidth * $el.data('aspectRatio')); 

    }); 

// Kick off one resize to fix all videos on page load 
}).resize(); 

您也可以参考这个网页它实际上是如何工作的,并也有动态视频重新调整为CSS和HTML例子好:

https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

+0

我会看看这个。我只是使用了一个