如何可靠且一致地获取 VIDEO 元素的计算宽度样式?
var vid = document.createElement("video");
vid.src = "big_buck_bunny_640x360.mp4";
document.getElementsByTagName("body")[0].appendChild(vid);
console.log(window.getComputedStyle(vid, null).getPropertyValue("width"));
控制台总是显示“300px”,但显然我正在寻找的值是“640px”。如果我在 console.log 调用上使用 setTimeout 并延迟 100 毫秒,则控制台中会显示正确的“640px”值。
不过,我宁愿不使用 setTimeout。是否有“正确”的方法来获得准确的计算样式值?
var vid = document.createElement("video");
vid.src = "big_buck_bunny_640x360.mp4";
document.getElementsByTagName("body")[0].appendChild(vid);
console.log(window.getComputedStyle(vid, null).getPropertyValue("width"));
The console invariably shows "300px," but obviously the value I'm looking for is "640px". If I use setTimeout on that console.log call with a delay of 100 milliseconds, the correct "640px" value shows up in the console.
I'd rather not use setTimeout, though. Is there a "proper" way to get the accurate calculated style value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想获取视频元素的固有宽度和高度,您应该获取
videoWidth
和videoHeight
。请参阅此文档If you want to get the intrinsic width and height of the video element, you should get the
videoWidth
and thevideoHeight
. See this documentation活动结束后您可以获取正确的videoHeight/videoWidth loadedmetadata 或者如果 readyState 属性大于或等于 1。
使用 jQuery 获取正确值的代码可能如下所示:
但请注意,并非所有浏览器都会立即开始获取视频。
You can get the correct videoHeight/videoWidth after the event loadedmetadata or if the readyState property is higher or equal 1.
The code to get the right value - using jQuery - could look like this:
But note, that, not all browser do start fetching the video immediately.