如何在jQuery中获取背景图片大小?

Foa*_*oad 52 css jquery

问题很简单.如何在jQuery中获取div的背景图像大小(宽度和高度).它甚至可能吗?我认为这会奏效:

jQuery('#myDiv').css('background-image').height();
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是这不是一个函数.

Vil*_*kas 87

还有一个版本.无需DOM操作,支持图像文件名中的所有字符.

更新请参阅下面的替代版本.

var image_url = $('#something').css('background-image'),
    image;

// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

if (image_url[1]) {
    image_url = image_url[1];
    image = new Image();

    // just in case it is not already loaded
    $(image).load(function () {
        alert(image.width + 'x' + image.height);
    });

    image.src = image_url;
}
Run Code Online (Sandbox Code Playgroud)

2018年解决方案

这个答案在5年之后仍然得到了回报.我想我会分享一个更完整的解决方案.它构建于原始代码之上,并将其包装到函数中.它使用jQuery的Deferred对象,增加了错误处理和更新正则表达式匹配3种可能情况:url(),url("")url('').它也适用于jQuery 1到3.

var getBackgroundImageSize = function(el) {
    var imageUrl = $(el).css('background-image').match(/^url\(["']?(.+?)["']?\)$/);
    var dfd = new $.Deferred();

    if (imageUrl) {
        var image = new Image();
        image.onload = dfd.resolve;
        image.onerror = dfd.reject;
        image.src = imageUrl[1];
    } else {
        dfd.reject();
    }

    return dfd.then(function() {
        return { width: this.width, height: this.height };
    });
};

//
// Usage
//
getBackgroundImageSize(jQuery('#mydiv'))
    .then(function(size) {
        console.log('Image size is', size.width, size.height);
    })
    .fail(function() {
        console.log('Could not get size because could not load image');
    });
Run Code Online (Sandbox Code Playgroud)

  • 潜在的陷阱:请参阅"与图像一起使用时加载事件的注意事项"http://api.jquery.com/load-event/ (4认同)
  • 没问题:)我相信你的应该是公认的答案.虽然其他人在大多数时间都会工作,但即使是最微不足道的人也会很脆弱.我不知道这会如何破坏,也不会增加不必要的复杂性. (2认同)
  • 这不适用于按比例缩小的图像(即,当使用 `background-size: contains;` 时) - 它提供“本机”图像属性,但不提供显示的图像属性。 (2认同)

Joh*_*lak 33

你必须做这样的事情:

var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
bgImg.bind('load', function()
{
    var height = $(this).height();
    alert(height);
});
$('#myDiv').append(bgImg);
bgImg.attr('src', url);
Run Code Online (Sandbox Code Playgroud)

由于代码简单,您不能在背景图像的URL中使用括号或引号.但是,可以扩展代码以获得更大的支持.我只是想传达一般的想法.

  • 最好替换所有''',这样你就可以使用:var url = $('#myDiv').css('background-image').replace('url(','').replace(' )','').replace(/'/ g,'').replace(/"/ g,''); (3认同)
  • 希望阅读这些答案的人阅读此评论.这个答案不是一个好习惯.将背景图像附加到DOM是一个错误,就像从#myDiv css中删除它一样.以这里检索的类似方式获取维度更容易,更快速,更安全,在下面的答案中做得更好,然后使用它们根据自己的喜好更改`background-size`属性. (3认同)

小智 29

迟到的答案,但你也可以这样做:

var img = new Image;
img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
Run Code Online (Sandbox Code Playgroud)

然后你不必操纵dom对象;