在 jQuery 中确定 Div 的背景图片尺寸
问题:
获取 div 的宽度和高度使用 jQuery 制作背景图像似乎难以捉摸。传统的尝试如 $('#myDiv').css('background-image').height();产生“不是函数”错误。
解决方案:
幸运的是,存在一个巧妙的解决方案。通过利用创建新 Image 对象的功能,即使 CSS 中没有明确定义图像尺寸,也可以确定图像尺寸。这是脚本的更新版本:
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; }
改进的方法(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中文网其他相关文章!