【问题标题】:Get background image's aspect ratio in jQuery在jQuery中获取背景图像的纵横比
【发布时间】:2016-10-06 15:14:08
【问题描述】:

客户有一个使用 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\((['"])?(.*?)\1\)/gi, '$2')
      .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());

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

【问题讨论】:

    标签: jquery image background background-image


    【解决方案1】:

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

    $(window).load(setBackgroundSize);
    

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

    【讨论】:

      【解决方案2】:

      或许你可以这样运行:

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

      希望我理解正确。

      【讨论】:

        猜你喜欢
        • 2018-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 1970-01-01
        相关资源
        最近更新 更多