如何使用 jQuery 確定 Div 的背景影像尺寸?
在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

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
如何修復KB5055518無法在Windows 10中安裝?
1 個月前
By DDD
如何修復KB5055523無法在Windows 11中安裝?
1 個月前
By DDD
<🎜>:種植花園 - 完整的突變指南
3 週前
By DDD
<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
如何修復KB5055612無法在Windows 10中安裝?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

您是否曾經在項目上需要一個倒計時計時器?對於這樣的東西,可以自然訪問插件,但實際上更多

我關注的一件事是Lea Verou&#039; s conic-Gradient()Polyfill的功能列表是最後一項:
