问题很简单。我如何在jQuery中获取div的背景图片大小(宽度和高度)?这是否可能?我认为下面这段代码会起作用:
jQuery('#myDiv').css('background-image').height();
我收到的错误消息是这不是一个函数。
还有一种版本。不需要DOM操作,支持在图像文件名中的所有字符。
更新 请查看下面的备选版本。
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;
}
这个回答在5年后仍然受到点赞。我想分享一个更完整的解决方案。它基于原始代码并将其封装成一个函数。它使用jQuery Deferred对象,添加了错误处理,并更新了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');
});
slice
是标准用法,substr
则不是;使用.slice(4, -1)
可以去除url(...)
。 - Dan Luggbackground-size: contain;
时)- 它提供了“本机”图像属性,但不是其显示的属性。 - kneidels你需要像这样做:
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);
由于代码的简单性,您不能在背景图像的URL中使用括号或引号。但是,该代码可以扩展以获得更大的支持。我只想传达一般想法。
background-size
属性以便符合你的需求。 - runspired虽然晚了些,但你也可以这样做:
var img = new Image;
img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
那么你就不需要操作dom对象了;
另一种简短的方式:
function bgSize($el, cb){
$('<img />')
.load(function(){ cb(this.width, this.height); })
.attr('src', $el.css('background-image').match(/^url\("?(.+?)"?\)$/)[1]);
}
使用方法
bgSize($('#element-with-background'), function(width, height){
console.log('width : ' + width + ' height : ' + height);
});
我将John的回答和Stryder的插件样式合并了。这个插件会等待图片加载:
$.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());
});
欢迎自由扩展这段代码:https://gist.github.com/1276118
var img = new Image ;
img.src = $('#dom').css('background-image').replace("url(", "").replace(")", "").replace("\"", "").replace("\"", "");
$(img).load(function() {
var bgImgWidth = img.width;
var bgImgHeight = img.height;
console.log("w::"+bgImgWidth+",h::"+bgImgHeight) ;
}) ;
$.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;
};
已经有一段时间了,但我也需要这个解决方案,基于一些建议的解决方案,这是我的完整解决方案。
$.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;
};
与上述方法相同,只是使用正则表达式而不是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();
});
$.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);
};
使用方法:
$("#image").getBgDim(function(dim) {
console.log("Height: " + dim.height + " Width: " + dim.width);
});
img
元素中,等待其加载完成后检查其尺寸。 - Pekka