2012-05-23 56 views
0

我正在設置頁面以顯示已創建的合成物的jpg,並且它們都具有不同的高度。使用JavaScript或jQuery你將如何根據背景圖片的高度自動調整div的高度? HTML代碼將簡單地進行佈局,像這樣:如何根據背景圖像更改div的高度?

<body> 
    <div id="comp"></div> 
</body> 

我知道你可以設置這是CSS,但我希望它是動態的,而不是必須添加高度每一次。感謝任何想法。

+1

我認爲它不可能找到使用jQuery – thecodeparadox

+1

這裏的背景圖像高度或寬度獲得的潛在方法背景圖片高度:http://stackoverflow.com/a/5106301/1028949 – Quantastical

+0

div是背景圖片的孩子嗎? – neuDev33

回答

1

也許這(未經測試)的代碼將幫助你看到它是如何可以做到:

// taken from the link in my comment to OP 
var url = $('body').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', ''); 
var bgImg = $('<img />'); 
bgImg.hide(); 
bgImg.attr('src', url); 
bgImg.bind('load', function() 
{ 
    var height = $(this).height(); 
    $('#comp').height(height); 
}); 
+0

我試過這個建議,但它返回了這個錯誤「ReferenceError:Can not find variable:$」 – doitliketyler

+0

[Look around](http://stackoverflow.com/questions/4888725/jquery-referenceerror-cant-find-variable)尋求答案來幫助你理解爲什麼會出現這個錯誤 – Quantastical