如何在 jQuery 中获取背景图像大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5106243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get background image size in jQuery?
提问by Foad
The problem is simple. How do I get a div's background image size (width and height) in jQuery. Is it even possible? I thought this would work:
问题很简单。如何在 jQuery 中获取 div 的背景图像大小(宽度和高度)。甚至有可能吗?我认为这会奏效:
jQuery('#myDiv').css('background-image').height();
The error message I get is that this is not a function.
我得到的错误消息是这不是一个函数。
采纳答案by John Kurlak
You'll have to do something like this:
你必须做这样的事情:
var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
bgImg.bind('load', function()
{
var height = $(this).height();
alert(height);
});
$('#myDiv').append(bgImg);
bgImg.attr('src', url);
Due to the simplicity of the code, you cannot use parenthesis or quotation marks in the URLs of your background images. However, the code could be extended for greater support. I just wanted to convey the general idea.
由于代码简单,您不能在背景图片的 URL 中使用括号或引号。但是,可以扩展代码以获得更大的支持。我只是想传达一般的想法。
回答by Vilius Paulauskas
One more version. No DOM manipulation needed, all characters in image file name supported.
再来一个版本。无需 DOM 操作,支持图像文件名中的所有字符。
UPDATESee an alternative version below.
更新请参阅下面的替代版本。
var image_url = $('#something').css('background-image'),
image;
// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);
if (image_url[1]) {
image_url = image_url[1];
image = new Image();
// just in case it is not already loaded
$(image).load(function () {
alert(image.width + 'x' + image.height);
});
image.src = image_url;
}
2018 solution
2018年解决方案
This answer is still receiving upvotes 5 years after. I thought I will share a more complete solution. This builds on top of original code and wraps it into a function. It uses jQuery Deferred Object, adds error handling and updates RegExp to match 3 possible cases: url()
, url("")
and url('')
. It also works on jQuery 1 to 3.
这个答案在 5 年后仍然受到好评。我想我会分享一个更完整的解决方案。这建立在原始代码之上,并将其包装成一个函数。它使用 jQuery 延迟对象,添加错误处理并更新 RegExp 以匹配 3 种可能的情况:url()
,url("")
和url('')
. 它也适用于 jQuery 1 到 3。
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 };
});
};
//
// 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');
});
回答by Jon
Late answer, but you could also do this:
迟到的答案,但你也可以这样做:
var img = new Image;
img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
Then you don't have to manipulate the dom objects;
那么你就不必操作 dom 对象了;
回答by Freez
Another short way :
另一个简短的方法:
function bgSize($el, cb){
$('<img />')
.load(function(){ cb(this.width, this.height); })
.attr('src', $el.css('background-image').match(/^url\("?(.+?)"?\)$/)[1]);
}
usage
用法
bgSize($('#element-with-background'), function(width, height){
console.log('width : ' + width + ' height : ' + height);
});
回答by schmidsi
I merged the answer from John together with the Plugin Style from Stryder. This plugin waits for the image to load:
我将 John 的答案与 Stryder 的 Plugin Style 合并在一起。此插件等待图像加载:
$.fn.getBgImage = function(callback) {
var height = 0;
var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = $('<img />');
tempImg.hide(); //hide image
tempImg.bind('load', callback);
$('body').append(tempImg); // add to DOM before </body>
tempImg.attr('src', path);
$('#tempImg').remove(); //remove from DOM
};
// usage
$("#background").getBgImage(function() {
console.log($(this).height());
});
feel free to extend this code: https://gist.github.com/1276118
随意扩展此代码:https: //gist.github.com/1276118
回答by Stryder
Its been a while but I needed this solution as well, based on some suggested solutions here is my complete solution.
已经有一段时间了,但我也需要这个解决方案,基于一些建议的解决方案,这里是我的完整解决方案。
$.fn.getBgHeight = function () {
var height = 0;
var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = '<img id="tempImg" src="' + path + '"/>';
$('body').append(tempImg); // add to DOM before </body>
$('#tempImg').hide(); //hide image
height = $('#tempImg').height(); //get height
$('#tempImg').remove(); //remove from DOM
return height;
};
回答by Jankeesvw
I made the same thing for the width :)
我为宽度做了同样的事情:)
$.fn.getBgWidth = function () {
var width = 0;
var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = '<img id="tempImg" src="' + path + '"/>';
$('body').append(tempImg); // add to DOM before </body>
$('#tempImg').hide(); //hide image
width = $('#tempImg').width(); //get width
$('#tempImg').remove(); //remove from DOM
return width;
};
回答by Capsule
css('background-image') will return "url(.....)", you can't test the height of the image with that, since it's not a DOM object.
css('background-image') 将返回“url(.....)”,你不能用它来测试图像的高度,因为它不是一个 DOM 对象。
回答by xramonz
the same as above, but using regexp instead of replace()
同上,但使用 regexp 而不是 replace()
$.fn.extend({
/**
* gets background image
* @param callback function (inside - this = HTMLElement image)
*/
get_bg_image: function(callback) {
if (typeof callback != 'function') return;
var regexp = /url\((.+)\)/i,
regexp2 = /["']/gi,
res = regexp.exec($(this).css('background-image')),
img_src = res[1].replace(regexp2, ''),
$tempImg = $('<img />');
$tempImg.hide();
$tempImg.bind('load', function(e) {
callback.call(this, e);
$tempImg.remove();
});
$('body').append($tempImg);
$tempImg.attr('src', img_src);
}
});
// usage
$('div').get_bg_image(function() {
var bg_img_width = $(this).width();
});
回答by Bas
The following is my adaptation:
以下是我的改编:
$.fn.getBgDim = function (callback) {
var width = 0,
height = 0,
path = $(this).css("background-image").replace("url(", "").replace(")", "").replace("\"", "").replace("\"", ""),
tmp = $("<img />");
tmp.hide();
tmp.bind("load", function() {
width = $(this).width();
height = $(this).height();
callback({"width": width, "height": height});
$(this).remove();
});
$("body").append(tmp);
tmp.attr('src', path);
};
Usage:
用法:
$("#image").getBgDim(function(dim) {
console.log("Height: " + dim.height + " Width: " + dim.width);
});