在 jQuery 中获取背景图片的纵横比

Get background image's aspect ratio in jQuery

客户有一个使用 Theme Hiker 的基于 WordPress 的网站。在 this 页面上,有一个画廊使用背景图片代替内联图片。

我需要确定那些图像的值超高比。如果比率小于 1,则将 background-size: contain 添加到满足该条件的每张幻灯片(列表元素)。

我做了这个功能:

function setBackgroundSize() {
    var $sliderItem = $(".full-photos li");
    $sliderItem.each(function(){
      var imageSrc = $(this).data('image-src');
      imageSrc.replace(/url\((['"])?(.*?)\)/gi, '')
      .split(',')[0];
      var image = new Image();
      image.src = imageSrc;
      var width = image.width,
      height = image.height,
      ratio = width/height;
      console.log(ratio);
      if (ratio < 1) {
        $(this).css('background-size', 'contain');
      }
    });
}
$(window).load(setBackgroundSize());

问题是它只有在页面加载后才有效,我刷新它。剧本有什么问题?谢谢!

$(window).load(setBackgroundSize()); 正在立即执行 setBackgroundSize 函数(在加载事件发生之前)。改为传递对函数的引用:

$(window).load(setBackgroundSize);

$(window).load(function() { setBackgroundSize(); });

也许你可以运行这样:

$(window).resize(function() { setBackgroundSize(); });

希望我理解正确。