【问题标题】:Get Width and Height of HTML5 Video using JavaScript?使用 JavaScript 获取 HTML5 视频的宽度和高度?
【发布时间】:2017-07-15 08:58:42
【问题描述】:

我已经尝试了几个在这里找到的答案。

此代码在 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(如果没有视频源,则默认播放器大小)

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    编辑:在我实际阅读跨浏览器问题后改进了解决方案。

    下面的解决方案应该适用于 Chrome 和 Firefox。问题在于 Firefox 对待 readyState 的方式与 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

    【讨论】:

    • 你能证明它返回 jsfiddle 中的值吗?我没有正确使用文档写入输出。
    • 它在 Chrome 中显示 Test 2: 640,但在 Firefox 中它是空白的。
    • 更新了我的答案,请检查
    • 它在 Firefox 和 Chrome 中都有效,但 IE11 不返回值。让我将此代码改编为我的项目并回复您。感谢您为此所做的工作。
    【解决方案2】:

    如果您尝试使用 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

    【讨论】:

    • 我会看看这个。我只是在使用
    猜你喜欢
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2023-03-04
    相关资源
    最近更新 更多