2014-05-13 22 views
0

我試圖獲取元素的高度和margin-bottom,並對它們進行計數。但到目前爲止,我只能做到這一點:jQuery計算2個不同的HTML元素屬性(高度+ margin-bottom)

var sum = $('div').height() + 25); 

25我不得不尋找自己在樣式表在

div { 
    height: 75px; 
    margin-bottom: 25px; 
} 

我怎樣才能使這個全自動?

,因爲當我嘗試:

var sum = $('div').height() + $('div').css('margin-bottom'); 

它不是返回任何值。

+0

你調試,看看它返回?它應該返回「一個價值」,而不是你想象的那樣。看看這個:http://stackoverflow.com/questions/1100503/how-to-get-just-numeric-part-of-css-property-with-jquery –

回答

3

您可能正在尋找http://api.jquery.com/outerheight/,其中包括邊距,填充和邊框(所有這些數字都指向總高度以及底部高度)。或者,您可以使用parseInt($('div').css('margin-bottom')),因爲該值是一個類似於以下內容的css字符串:100pxparseInt()會從該css中提取100,這正是您想要的。

此外,你有點做錯了一般。你在尋找所有div元素的所有高度的總和嗎?或者你的網頁只有一個div?

+0

是的:D謝謝你,不能接受你的答案但是,我會:) – Bas

+0

僅供參考:如果你想總結所有'div'的height()(或'outerHeight()'),你應該看看jquery的'each'(http ://api.jquery.com/each/) –

0

文檔中有很多'div'元素(通常是)。 您需要更好的選擇器。 Fiddle for value in console.log

<div id="TestId" class="test"></div> 

.test 
{ 
height:40px; 
margin:5px; 
} 

var tester = $("#TestId"); 
var eleHeight = tester.outerHeight(); 
var marginBottomHeight = tester.css('margin-bottom').replace("px", "") 
console.log(eleHeight + parseInt(marginBottomHeight));  
+0

這是一個例子......:P – Bas

0

$('div').css('margin-bottom')將有PX連接。嘗試使用類似parseInt()

var sum = $('div').height() + parseInt($('div').css('margin-bottom'), 10); 

W¯¯