【问题标题】:Getting dimensions of background-image获取背景图像的尺寸
【发布时间】:2017-05-05 19:06:00
【问题描述】:

我正在尝试获取元素背景图像的宽度和高度。当您单击它时,它应该在元素内显示它(在本例中为“200 300”)。

HTML:

<div id='test'></div>

CSS:

#test {
  width: 100px; height: 100px;
  background-image: url(http://placehold.it/200x300);
}

JavaScript:

$('#test').on('click', function () {
  $(this).text(getDimensions($(this)));
});

var getDimensions = function(item) {
  var img = new Image(); //Create new image
  img.src = item.css('background-image').replace(/url\(|\)$/ig, ''); //Source = clicked element background-image
  return img.width + ' ' + img.height; //Return dimensions
};

这是Fiddle。问题是它只能在 Chrome 中运行,所有其他主要浏览器都返回“0 0”。我不知道是什么原因。那张图不是已经满载了吗?

【问题讨论】:

    标签: javascript google-chrome cross-browser background-image


    【解决方案1】:

    问题是某些浏览器在 CSS 中添加引号,并且它试图加载(在小提琴的情况下)“http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22”。我已经更新了你的 .replace() 以寻找 " 以及一个小提琴在http://jsfiddle.net/4uMEq/

    $('#test').on('click', function () {
        $(this).text(getDimensions($(this)));
    });
    
    var getDimensions = function (item) {
        var img = new Image();
        img.src = item.css('background-image').replace(/url\(|\)$|"/ig, '');
        return img.width + ' ' + img.height;
    };
    

    【讨论】:

    • 谢谢,我从没想到这是问题所在。
    • 如果有疑问,请打开网络检查器和console.log() ;) 告诉我的是 FF 无法加载带有那个奇怪 URL 的图像。
    【解决方案2】:

    我猜你需要等待图像上的onload 事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多