【问题标题】:Get the original dimensions of a <video>获取 <video> 的原始尺寸
【发布时间】:2015-07-02 19:21:25
【问题描述】:

我正在尝试创建一个视频和图片列表,每个都调整为相同大小以便于查看。

当用户点击其中一个时,应将其调整为原始大小(或最大边界框的大小)

我的问题是:我如何获得视频的原始尺寸?

对于图片,

var img = new Image();
img.src= $(event.target).attr("src");
img.width   //this is the width
img.height  //this is the height

像魅力一样工作。

但我找不到对&lt;video&gt; 执行相同操作的方法。有吗?

我知道加载元数据有一些问题,但视频已经加载,我只想将其调整为原始大小(我不会在调整大小时延迟加载它们,但我想这更多努力)

可以这样做吗?如果是这样,如何? 首选 jQuery。

解决方案:

var video = $(event.target);
var width = video[0].videoWidth;

【问题讨论】:

    标签: jquery html video resize size


    【解决方案1】:

    您可以使用原生 Javascript 做到这一点:

    var video = $("#myvideo" ); //JQuery selector 
    video[0].videoWidth; //get the original width
    video[0].videoHeight; //get the original height
    

    也了解一下:

    video[0].width; //get or set width for the element in DOM
    video[0].height; //get or set height for the element in DOM
    

    有关更多信息,您可以查看 W3 中的这些链接: videoWidth , videoHeight

    【讨论】:

    • var video = $(event.target); console.log(video.videoWidth);是“未定义”:(但它适用于 video[0].videoWidth。谢谢 :)
    • 你是对的,这是我的错误,我会编辑答案,不客气:))。
    【解决方案2】:

    发布的解决方案对我不起作用。如果有人有同样的问题,我的解决方案可能会有所帮助。

    const video = document.getElementById("myVid")
    
    video.addEventListener('loadeddata', function(e) {
        let width = e.target.videoWidth
        let height = e.target.videoHeight
    
        let elWidth = e.target.width
        let elHeight = e.target.height
    
     }, false)
    

    查看https://codepen.io/guerrato/pen/aYNeaW

    【讨论】:

      【解决方案3】:

      我注意到,在加载元数据之前,您会得到错误的结果...如果您想确定,请等待元数据加载事件,然后获取 videoHeight 和 videoWidth!

      yourVideoElement.addEventListener( "loadedmetadata", function (e) {
              console.log(this.videoHeight);
              console.log(this.videoWidth);
          }, false );
      

      【讨论】:

        【解决方案4】:

        试试这个

        $(function(){
          $('#my_video').bind('loadedmetadata', function(){
            var rawWidth = $(this).prop('videoWidth'); 
            var rawHeight = $(this).prop('videoHeight');
            $("#result").html('Height: '+rawHeight+'; Width: '+rawWidth);  
          });
        });
        

        【讨论】:

          猜你喜欢
          • 2020-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-04
          • 1970-01-01
          • 2013-04-17
          相关资源
          最近更新 更多