使用原生 JavaScript 获取 HTML5 视频的宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16272924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get width and height of HTML5 Video using native JavaScript
提问by kav
I am trying to get width and height of tag, I am using the following markup:
我正在尝试获取标签的宽度和高度,我正在使用以下标记:
<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>
The key part is that width and height attributes are both set to 100%, and when window is changed aspect ratio of video is saved, but I cannot get it's actual width and height.
关键是宽度和高度属性都设置为100%,当窗口改变时,视频的纵横比被保存,但我无法得到它的实际宽度和高度。
I tried to get value using offsetWidth and offsetHeight properties, but they are return actual size of the video.
我尝试使用 offsetWidth 和 offsetHeight 属性获取值,但它们返回视频的实际大小。
Edit:
编辑:
This is the piece of code that working for me:
这是对我有用的代码:
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%");
}
Thanks!
谢谢!
回答by Karim Lee
This code will give you the dimensions of the video tag (not the dimensions of the video itself)
此代码将为您提供视频标签的尺寸(不是视频本身的尺寸)
var video = document.getElementById("video");
var videotag_width = video.offsetWidth;
var videotag_height = video.offsetHeight;
This code will give you the dimensions of the video that is currently playing
此代码将为您提供当前正在播放的视频的尺寸
var video = document.getElementById("video");
var video_height = video.videoHeight;
var video_width = video.videoWidth;