You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jQuery在视频加载完成前获取其在移动端浏览器的渲染高度

解决移动端视频加载前获取object-fit:contain渲染高度的问题

嘿,这个问题我之前做移动端视频交互的时候也碰到过,8MB的视频等完全加载完再拿高度确实太拖慢体验了,给你几个实用的解决思路:

方案一:利用视频的loadedmetadata事件(推荐,无需提前知道视频宽高)

视频的元数据(包括原始宽高、时长这些信息)体积很小,会比整个视频内容先加载完成。我们可以监听loadedmetadata事件,拿到视频的原始宽高后,结合容器的实际宽度,按照object-fit:contain的规则计算出渲染高度,不用等整个视频下载完。

代码示例:

jQuery(document).ready(function($){
  function calculateVidRenderHeight() {
    const videoEl = $('#section-feature-device video')[0];
    const containerWidth = videoEl.offsetWidth; // 获取视频容器的实际宽度
    const videoNaturalWidth = videoEl.videoWidth; // 视频原始宽度
    const videoNaturalHeight = videoEl.videoHeight; // 视频原始高度

    // 按照object-fit:contain的逻辑计算渲染高度
    const videoAspectRatio = videoNaturalWidth / videoNaturalHeight;
    let renderHeight = containerWidth / videoAspectRatio;

    // 给叠加容器设置高度
    $(".elementor-element-0113321").css("height", `${renderHeight}px`);
  }

  $(window).on('load resize', function() {
    if ($(this).width() <= 767) {
      const videoEl = $('#section-feature-device video')[0];
      // 如果视频元数据已经加载完成,直接计算
      if (videoEl.readyState >= 2) {
        calculateVidRenderHeight();
      } else {
        // 否则监听元数据加载事件
        videoEl.addEventListener('loadedmetadata', calculateVidRenderHeight);
      }
    }
  });
});

这个方法的优势是触发时机早,元数据加载通常只需要几百毫秒,远快于整个视频加载完成。

方案二:硬编码视频宽高比(最快,适合固定视频的场景)

如果你确定这个视频的宽高比是固定的(比如一直是16:9),那可以直接把宽高比写进代码里,不用等任何加载事件,页面渲染后就能直接计算出高度。

代码示例:

jQuery(document).ready(function($){
  function calculateVidRenderHeight() {
    const containerWidth = $('#section-feature-device video').offsetWidth;
    const videoAspectRatio = 16 / 9; // 替换成你的视频实际宽高比
    const renderHeight = containerWidth / videoAspectRatio;
    $(".elementor-element-0113321").css("height", `${renderHeight}px`);
  }

  $(window).on('load resize', function() {
    if ($(this).width() <= 767) {
      calculateVidRenderHeight();
    }
  });
});

这个方案是最快的,完全不需要等待视频相关的加载,适合视频内容固定的场景。

方案三:利用视频poster图(适合已设置poster的场景)

如果你的视频已经设置了poster属性,那么poster图的渲染逻辑和视频是完全一致的(同样遵循object-fit:contain),而且图片加载速度远快于视频。我们可以直接获取poster图的高度来设置叠加容器。

首先确保视频标签有poster属性:

<video id="section-feature-device" poster="your-poster-image.jpg" style="object-fit:contain;"></video>

然后代码:

jQuery(document).ready(function($){
  function setOverlayHeight() {
    const videoHeight = $('#section-feature-device video').height();
    $(".elementor-element-0113321").css("height", `${videoHeight}px`);
  }

  $(window).on('load resize', function() {
    if ($(this).width() <= 767) {
      setOverlayHeight();
    }
  });
});

这个方法简单直接,前提是你已经为视频配置了合适的poster图。

内容的提问来源于stack exchange,提问作者WebMW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:14:11