2012-05-31 113 views
2

我有一個帶背景圖像的DIV。但我的要求是如何根據背景圖像的高度和寬度來擴展DIV大小。我在this鏈接的幫助下嘗試了一些代碼。如何根據背景圖像的高度和寬度設置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(); 

我只是尋找任何優雅的解決方案,如果可能的話。

回答

5

你可能只需要尋找寬/高的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); 
+0

它有很大的幫助。 – Exception

0

我會先加載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/

相關問題