繁体   English   中英

jQuery添加两个CSS属性值

[英]jQuery add two CSS property values

我试图获取元素的顶部位置和margin-bottom值。
工作的:

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

芽,我需要为动画功能添加这些。 所以top+margin但jQuery给出-540 px,但是它需要返回-54 px ..或者当它的负数时,它只给出-54-10px,而我需要-64 px。

有东西可以解决这个问题吗? 我想不出来,这让我很烦!

我的代码:

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

var combine = top+margin;

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

芽,我需要为我的动画功能添加这些。 所以top + margin但jQuery给540 p

css值是字符串,因此,由于您的操作数之一是字符串,因此+被解释为连接运算符( 54 + "0" = "540" ),而不是加法运算符。 (详细信息)要将它们转换为数字,请使用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});

这是因为它以字符串形式返回值,并在它们上使用+运算符进行连接。 您可以使用parseInt从字符串中获取数字。 如果有px后缀,它甚至可以工作,尽管会在此停止。

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

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM