2012-01-16 122 views
1

我試圖獲取元素的頂部位置和margin-bottom值。
奏效:jQuery添加兩個CSS屬性值

var top = -$('elem').postion().top; // lets say its -54 
var margin = $('elem').css('margin-top'); // lets say its 0 

芽我需要添加這些爲我的動畫功能。所以top+margin,但jQuery給出-540像素,但它需要返回-54像素..或者當它的負面它只是給-54-10px當我需要-64像素。

有沒有辦法解決這個問題?我無法想出它,它讓我很煩惱!

我的代碼:

var top = -$('#id1').position().top; 
var margin = $('.scrollable').css('margin-top'); 

var combine = top+margin; 

$('.animate').animate({'margin-top' : combine}); 
+0

第二個是一個字符串(例如:「10px的」)... – 2012-01-16 15:20:44

回答

6

芽我需要添加這些爲我的動畫功能。所以頂部+保證金,但jQuery的給540 p

css值是字符串,那麼因爲你的一個操作數是一個字符串,該+被解釋爲一個連接符(54 + "0" = "540"),而不是加法運算符。 (Details)把它們變成號碼,使用parseInt(str, 10),例如:

// I believe `top` will already be a number; check and if not, use parseInt here too, 
// e.g. var top = -parseInt($('#id1').position().top, 10); 
var top = -$('#id1').position().top; 

// This will definitely be a string that needs parsing; note that we're assuming 
// here that the margin has been given in `px` units. 
var margin = parseInt($('.scrollable').css('margin-top'), 10); 

// Now this + is an addition, not a concatenation  
var combine = top+margin; 

$('.animate').animate({'margin-top' : -combine}); 
+1

+1不忘約10參數 – Misiur 2012-01-16 15:21:45

+0

@Misiur是不是默認的轉換反正? – 2012-01-16 15:22:21

+0

或使用'+ str'轉換爲數字 – Raynos 2012-01-16 15:22:41

0

試試這個

var combine = parseInt(top) + parseInt(margin); 
3

這是因爲它返回的值作爲字符串,並使用+運營商對它們會連接。您可以使用parseInt從字符串中獲取數字。如果後綴爲px,它甚至會工作,儘管它會停止。

var top = $('elem').postion().top; 
var margin = $('elem').css('margin-top'); 

var total = parseInt(top, 10) + parseInt(margin, 10); 
+0

'parseInt(margin,10);';) – Raynos 2012-01-16 15:24:35

+0

重要的用法'parseFloat'或'parseInt(int,10);' – noob 2012-01-16 15:26:03

+0

是的,固定的。謝謝。 – 2012-01-16 15:26:21