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

Exc*_*ion 2 javascript jquery

我有一个背景图像的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();
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*ing 5

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

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

此外,您不需要附加它,创建一个新图像就足够了.我是这样做的:

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);
Run Code Online (Sandbox Code Playgroud)