使用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(如果没有视频源,则默认玩家大小)

编辑:我实际阅读CrossBrowser问题后改进的解决方案。

下面的解决方案应在Chrome和Firefox上起作用。问题是,Firefox对准备状态的对待与Chrome不同。

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

如果您试图用java脚本定义视频的大小,我不确定您实际上要做什么这个示例。

如果我们假定视频已嵌入,以下代码可能会执行技巧

// 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

最新更新