使用原生JavaScript获取HTML5视频的宽度和高度

Get width and height of HTML5 Video using native JavaScript

本文关键字:高度 视频 HTML5 原生 JavaScript 获取      更新时间:2023-09-26

我正在尝试获得标签的宽度和高度,我使用以下标记:

<div class="masked" id="video_container">
    <video id="video" loop="loop" muted="muted" tabindex="0" style="width: 100%; height: 100%;">
        <source src="..." type="..."</source>
        <source src="..." type="..."</source>
    </video>
</div>

关键部分是宽度和高度属性都设置为100%,当窗口改变时视频的长宽比被保存,但我无法得到它的实际宽度和高度。

我尝试使用offsetWidth和offsetHeight属性获得值,但它们返回视频的实际大小。

编辑:

这段代码为我工作:

var videoActualWidth = video.getBoundingClientRect().width;
var videoActualHeight = video.getBoundingClientRect().height;
var aspect = videoActualWidth / videoActualHeight;
if (w / h > aspect) {
    video.setAttribute("style", "height: 100%");
} else {
    video.setAttribute("style", "width: 100%");
}

谢谢!

这段代码将为您提供视频标签的尺寸(而不是视频本身的尺寸)

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

此代码将为您提供当前正在播放的视频的尺寸

var video = document.getElementById("video");
var video_height = video.videoHeight;
var video_width = video.videoWidth;