Home > Web Front-end > CSS Tutorial > How to Get a Div's Background Image Dimensions Using jQuery?

How to Get a Div's Background Image Dimensions Using jQuery?

Susan Sarandon
Release: 2024-12-13 20:20:12
Original
781 people have browsed it

How to Get a Div's Background Image Dimensions Using jQuery?

Determine Background Image Dimensions with jQuery

Introduction

Retrieving the dimensions of a div's background image using jQuery may seem straightforward but poses challenges. This article tackles this task and presents an extended solution that simplifies the process.

Questions:

Query: How can I obtain the background image size (width and height) of a div using jQuery?

Response A:

To retrieve the background image dimensions, employ the following approach:

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

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

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

    // Load image if needed
    $(image).load(function () {
        alert(image.width + 'x' + image.height);
    });

    image.src = image_url;
}
Copy after login

Response B (2018 Update):

For a comprehensive solution:

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 };
    });
};
Copy after login

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

The above is the detailed content of How to Get a Div's Background Image Dimensions Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template