How do I get background image size in jQuery?

2019-01-02 15:29发布

The problem is simple. How do I get a div's background image size (width and height) in jQuery. Is it even possible? I thought this would work:

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

The error message I get is that this is not a function.

标签: jquery css
14条回答
孤独总比滥情好
2楼-- · 2019-01-02 15:51

I merged the answer from John together with the Plugin Style from Stryder. This plugin waits for the image to load:

$.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());
});

feel free to extend this code: https://gist.github.com/1276118

查看更多
春风洒进眼中
3楼-- · 2019-01-02 15:52

Combined version of the above solutions

var width,
    height;

$(image).load(function () {
    width  = image.width;
    height = image.height;
});

image.src = $('#id').css('background-image').replace(/url\(|\)$/ig, "");
查看更多
看风景的人
4楼-- · 2019-01-02 15:59

One more version. No DOM manipulation needed, all characters in image file name supported.

UPDATE See an alternative version below.

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 solution

This answer is still receiving upvotes 5 years after. I thought I will share a more complete solution. This builds on top of original code and wraps it into a function. It uses jQuery Deferred Object, adds error handling and updates RegExp to match 3 possible cases: url(), url("") and url(''). It also works on jQuery 1 to 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');
    });
查看更多
路过你的时光
5楼-- · 2019-01-02 16:00

In the case your css had double quotes or browser manipulation do the following.

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);
查看更多
无与为乐者.
6楼-- · 2019-01-02 16:01

I made the same thing for the width :)

$.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;
};
查看更多
还给你的自由
7楼-- · 2019-01-02 16:02

the same as above, but using regexp instead of 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();
});
查看更多
登录 后发表回答