首頁 > web前端 > css教學 > 如何使用 jQuery 確定 Div 的背景影像尺寸?

如何使用 jQuery 確定 Div 的背景影像尺寸?

DDD
發布: 2025-01-01 04:59:10
原創
273 人瀏覽過

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

在jQuery 中確定Div 的背景圖片尺寸

問題:

問題:獲得div 的寬度和高度使用jQuery 製作背景圖像似乎難以捉摸。傳統的嘗試如 $('#myDiv').css('background-image').height();產生「不是函數」錯誤。

解決方案:
var image_url = $('#something').css('background-image'),
    image;

// Extract the URL without the url() or url("") wrapper
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

// Proceed if the image URL was obtained
if (image_url[1]) {
    image_url = image_url[1];
    // Create a new Image object
    image = new Image();

    // Trigger an event when the image is loaded
    // This ensures we get the actual image dimensions
    $(image).load(function () {
        alert('Width: ' + image.width + '\nHeight: ' + image.height);
    });

    image.src = image_url;
}
登入後複製

幸運的是,存在一個巧妙的解決方案。透過利用創建新 Image 物件的功能,即使 CSS 中沒有明確定義圖像尺寸,也可以確定圖像尺寸。這是腳本的更新版本:

改進的方法(2018):
var getBackgroundImageSize = function(el) {
    // Extract the image URL
    var imageUrl = $(el).css('background-image').match(/^url\(["']?(.+?)["']?\)$/);
    // Create a deferred object
    var dfd = new $.Deferred();

    // Handle existence of image URL
    if (imageUrl) {
        // Create a new Image object
        var image = new Image();
        // Resolve the deferred on load, reject on error
        image.onload = dfd.resolve;
        image.onerror = dfd.reject;
        // Assign the image source
        image.src = imageUrl[1];
    } else {
        // Image not available, reject
        dfd.reject();
    }

    // Return the dimensions if the image loads
    return dfd.then(function() {
        // Return the dimensions as an object
        return { width: this.width, height: this.height };
    });
};

// Sample usage
getBackgroundImageSize(jQuery('#mydiv'))
    .then(function(size) {
        // Success - log the dimensions
        console.log('Image size is: ', size);
    })
    .fail(function() {
        // Error - log failure message
        console.log('Failed to determine image size');
    });
登入後複製
下面提供了更全面的解決方案,提供增強的功能和錯誤處理:

以上是如何使用 jQuery 確定 Div 的背景影像尺寸?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板