如何根据背景图像的高度和宽度设置 DIV 尺寸

How to set DIV dimensions as per the height and width of background-image

本文关键字:设置 DIV 尺寸 高度 何根 背景 图像      更新时间:2023-09-26

我有一个带有背景图像的DIV。但我的要求是如何根据背景图像的高度和宽度扩展 DIV 大小。我在此链接的帮助下尝试了一些代码。

var src = $('#divID').css('background-image').
                      replace('url', '')
                     .replace('(', '')
                     .replace(')', '')
                     .replace('"', '')
                     .replace('"', '');
$('body').append('<img id="appendedImg" src="' + src + '" style="height:0px;width:0px"');
var img = document.getElementById('appendedImg');       
var width = img.clientWidth;
var height = img.clientHeight; 
$('#appendedImg').detach();

如果可能的话,我只是在寻找任何优雅的解决方案。

您可能只需要在加载时查找宽度/高度:

var img = document.getElementById('appendedImg');
img.onload = function() {   
    var width = img.width;
    var height = img.height;
    console.log(width,height);
};

另外,您不需要附加它,创建新图像应该就足够了。以下是我会怎么做:

var $div = $('#divID'),
    src = $div.css('background-image').replace(/url'('"([^'"]+).*/,'$1');
$(new Image).load(function() {
    $div.width(this.width).height(this.height);
}).attr('src', src);

我会先加载img,然后获取其高度和宽度:

imgSrc = 'http://ajthomas.co.uk/wp-content/themes/ajthomascouk/library/images/logo.png'
// append the temp imag
$('body').append('<img src="'+imgSrc+'" alt="" style="display:none" id="dummyImage"/>');
// get the image width and height
imgWidth = $('#dummyImage').width()+'px';
imgHeight = $('#dummyImage').height()+'px';
// remove the image
$('#dummyImage').remove();
// set the css for the div
$('#imADiv').css({height: imgHeight, width: imgWidth, 'background-image': 'url('+imgSrc+')'});

在这里为您编码 - http://jsfiddle.net/LTdtM/