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

56

问题很简单。我如何在jQuery中获取div的背景图片大小(宽度和高度)?这是否可能?我认为下面这段代码会起作用:

jQuery('#myDiv').css('background-image').height();

我收到的错误消息是这不是一个函数。


背景是固定的吗?它会随着窗口的大小而调整大小,还是您只想知道绑定为背景信息的图像? - Brad Christie
2
你需要将背景图片加载到一个 img 元素中,等待其加载完成后检查其尺寸。 - Pekka
不,背景图像不是固定的。它会随着窗口大小调整。背景图像居中且为100x100像素,但周围的div为500x500像素。我该如何获得宽度100和高度100? - Foad
17个回答

91

还有一种版本。不需要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;
}

2018年解决方案

这个回答在5年后仍然受到点赞。我想分享一个更完整的解决方案。它基于原始代码并将其封装成一个函数。它使用jQuery Deferred对象,添加了错误处理,并更新了RegExp以匹配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');
    });

1
slice是标准用法,substr则不是;使用.slice(4, -1)可以去除url(...) - Dan Lugg
2
没问题 :) 我相信你的答案应该被接受。虽然其他人的方法大多数情况下都能工作,但即使是最琐碎的方法也可能很脆弱。我不认为这种方法会出错,也不会增加不必要的复杂性。 - Dan Lugg
4
潜在陷阱:请参考“使用图像时加载事件的注意事项”http://api.jquery.com/load-event/ - Andy
我只能使用imagesLoaded jQuery插件才能使其正常工作。 - Reed Martin
2
这不适用于缩小比例的图像(即使用background-size: contain;时)- 它提供了“本机”图像属性,但不是其显示的属性。 - kneidels

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);

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


3
最好替换所有的'"'符号,这样您就可以使用以下代码: var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace(/'/g, '').replace(/"/g, ''); - Jimmy Huang
3
希望阅读这些答案的人能够看到这条评论。这个答案并不是一个好的实践方法。将背景图添加到DOM中是一个错误,同样也是从#myDiv css中删除它的错误。更容易、更快速且更安全的方法是以类似于下面回答所检索的方式获取尺寸,然后使用它们来改变 background-size 属性以便符合你的需求。 - runspired

29

虽然晚了些,但你也可以这样做:

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

那么你就不需要操作dom对象了;


这个特定的方法会创建一个服务器请求吗?还是从内存中获取数据? - Mike Kormendy
@Mike Kormendy,这个答案处理当前请求。它不会创建一个新的请求。 - Kirby

4

另一种简短的方式:

function bgSize($el, cb){
    $('<img />')
        .load(function(){ cb(this.width, this.height); })
        .attr('src', $el.css('background-image').match(/^url\("?(.+?)"?\)$/)[1]);
}

使用方法

bgSize($('#element-with-background'), function(width, height){
    console.log('width : ' + width + ' height : ' + height);
});

https://jsfiddle.net/x4u2ndha/58/


3

我将John的回答和Stryder的插件样式合并了。这个插件会等待图片加载:

$.fn.getBgImage = function(callback) {
    var height = 0;
    var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
    var tempImg = $('<img />');
    tempImg.hide(); //hide image
    tempImg.bind('load', callback);
    $('body').append(tempImg); // add to DOM before </body>
    tempImg.attr('src', path);
    $('#tempImg').remove(); //remove from DOM
};


// usage
$("#background").getBgImage(function() {
    console.log($(this).height());
});

欢迎自由扩展这段代码:https://gist.github.com/1276118


2
也许只有少数可能性,我尽力简化了这个过程,最终对我来说是有效的。
var img = new Image ;
img.src = $('#dom').css('background-image').replace("url(", "").replace(")", "").replace("\"", "").replace("\"", "");
$(img).load(function() {
    var bgImgWidth = img.width;
    var bgImgHeight = img.height;
    console.log("w::"+bgImgWidth+",h::"+bgImgHeight) ;
}) ;

2
我也为宽度做了同样的事情 :)
$.fn.getBgWidth = function () {
    var width = 0;
    var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
    var tempImg = '<img id="tempImg" src="' + path + '"/>';
    $('body').append(tempImg); // add to DOM before </body>
    $('#tempImg').hide(); //hide image
    width = $('#tempImg').width(); //get width
    $('#tempImg').remove(); //remove from DOM
    return width;
};

2

已经有一段时间了,但我也需要这个解决方案,基于一些建议的解决方案,这是我的完整解决方案。

$.fn.getBgHeight = function () {
        var height = 0;
        var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
        var tempImg = '<img id="tempImg" src="' + path + '"/>';
        $('body').append(tempImg); // add to DOM before </body>
        $('#tempImg').hide(); //hide image
        height = $('#tempImg').height(); //get height
        $('#tempImg').remove(); //remove from DOM
        return height;
    };

1

与上述方法相同,只是使用正则表达式而不是replace()

$.fn.extend({
    /**
     * gets background image
     * @param callback function (inside - this = HTMLElement image)
     */
    get_bg_image: function(callback) {
        if (typeof callback != 'function') return;
        var regexp = /url\((.+)\)/i,
            regexp2 = /["']/gi,
            res = regexp.exec($(this).css('background-image')),
            img_src = res[1].replace(regexp2, ''),
            $tempImg = $('<img />');
        $tempImg.hide();
        $tempImg.bind('load', function(e) {
            callback.call(this, e);
            $tempImg.remove();
        });
        $('body').append($tempImg);
        $tempImg.attr('src', img_src);
    }
});

// usage
$('div').get_bg_image(function() {
    var bg_img_width = $(this).width();
});

1
以下是我的改编:
$.fn.getBgDim = function (callback) {
    var width  = 0,
        height = 0,
        path   = $(this).css("background-image").replace("url(", "").replace(")", "").replace("\"", "").replace("\"", ""),
        tmp    = $("<img />");
    tmp.hide();
    tmp.bind("load", function() {
        width = $(this).width(); 
        height = $(this).height();
        callback({"width": width, "height": height});
        $(this).remove();
    });
    $("body").append(tmp);
    tmp.attr('src', path);
};

使用方法:

$("#image").getBgDim(function(dim) {
    console.log("Height: " + dim.height + " Width: " + dim.width);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接