【问题标题】:Random fails trying to get the naturalHeight and naturalWidth of an imageRandom 尝试获取图像的 naturalHeight 和 naturalWidth 失败
【发布时间】:2022-09-27 19:31:00
【问题描述】:

我有一些简单的代码来检查图像的宽度和高度,如果它不是 >= 120x90,它会得到一个visibility: hidden 放在上面。

$(\".video-thumbnail\").each(function () {
    var width = $(this).prop(\"naturalWidth\");
    var height = $(this).prop(\"naturalHeight\");

    if (width <= 120 && height <= 90) {
        $(this).css(\"visibility\", \"hidden\");
    }
});

问题是这在某些页面重新加载甚至某些硬重新加载时随机失败。这是随机的,所以这就是我寻求帮助的原因。

我认为这可能是一个缓存问题。

编辑

可以确认是缓存问题。 jQuery 没有在随机后续页面加载时获得prop(naturalWidth/naturalHeight)。所以我认为解决方案是强制重新加载图像(在每次访问页面时!?是的)。

有什么建议可以更可靠地运行吗?也许力量浏览器下载图像文件?不知道那会是什么样子。

    标签: javascript jquery


    【解决方案1】:

    更可靠的解决方案是使用HTMLImageElement.decode(),它返回一个承诺,一旦全分辨率图像可供使用,该承诺就会被解决,下面是一个示例:

    $(".video-thumbnail").each(function () {
      this.decode().then(() => {
          var width = $(this).prop("naturalWidth");
          var height = $(this).prop("naturalHeight");
    
          if (width <= 120 && height <= 90) {
              $(this).css("visibility", "hidden");
          }
      }).catch((encodingError) => {
        // Do something with the error.
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <img src="https://picsum.photos/121/91" class="video-thumbnail">
    <img src="https://picsum.photos/121/91" class="video-thumbnail">
    <img src="https://picsum.photos/119/89" class="video-thumbnail">
    <img src="https://picsum.photos/121/91" class="video-thumbnail">

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多