如何使用 jQuery 确定 Div 的背景图像尺寸?
Jan 01, 2025 am 04:59 AM在 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中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章标签

记事本++7.3.1
好用且免费的代码编辑器

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

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)