Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

css - How do I get background image size in jQuery?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...