2012-01-16 79 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