问题很简单.如何在jQuery中获取div的背景图像大小(宽度和高度).它甚至可能吗?我认为这会奏效:
jQuery('#myDiv').css('background-image').height();
Run Code Online (Sandbox Code Playgroud)
我得到的错误信息是这不是一个函数.
Vil*_*kas 87
还有一个版本.无需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;
}
Run Code Online (Sandbox Code Playgroud)
这个答案在5年之后仍然得到了回报.我想我会分享一个更完整的解决方案.它构建于原始代码之上,并将其包装到函数中.它使用jQuery的Deferred对象,增加了错误处理和更新正则表达式匹配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');
});
Run Code Online (Sandbox Code Playgroud)
Joh*_*lak 33
你必须做这样的事情:
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);
Run Code Online (Sandbox Code Playgroud)
由于代码简单,您不能在背景图像的URL中使用括号或引号.但是,可以扩展代码以获得更大的支持.我只是想传达一般的想法.
小智 29
迟到的答案,但你也可以这样做:
var img = new Image;
img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
Run Code Online (Sandbox Code Playgroud)
然后你不必操纵dom对象;
| 归档时间: |
|
| 查看次数: |
77978 次 |
| 最近记录: |