Red*_*nas 1 javascript math jquery
我试图获得元素的顶部位置和边距底值.
有效:
var top = -$('elem').postion().top; // lets say its -54
var margin = $('elem').css('margin-top'); // lets say its 0
Run Code Online (Sandbox Code Playgroud)
我需要为我的动画功能添加它们.所以top+marginjQuery给出-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});
Run Code Online (Sandbox Code Playgroud)
我需要为我的动画功能添加这些.所以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});
Run Code Online (Sandbox Code Playgroud)