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

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

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

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

您可能只需要查找宽度/高度onload:

 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(''); // 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(https://stackoverflow.com/questions/10830895/how-to-set-div-dimensions-as-per-the-height-and-width-of-background-image/'+imgSrc+')'}); 

在这里为你编写代码 – http://jsfiddle.net/LTdtM/