2011-10-02 35 views
0

鉴于这种代码的变量:计算数量,而不在JavaScript

if(ipadmenuheight < contentheight).css('top', '' + contentheight + 44 + 'px'); 

比方说contentheight=500

那么这个代码片断返回50044px。它怎么可能是一笔钱,并返回544px

我需要使用一个变量还是可以这样做内联?

回答

4

使用括号将两个数字相加。如果不是,他们将被追加为字符串:

...css('top', (contentheight + 44) + 'px'); 

顺便说一句,是不是需要先空字符串'',所以你也可以这样做:

...css('top', contentheight + 44 + 'px'); 
+0

'contentheight + 44 +'px''是否也能工作?我的意思是,'+'只是在这里造成麻烦。 – pimvdb

+0

是的,你是对的。我已经更新了答案。 –

2

使用括号强制数字加法:

('top', '' + (contentheight + 44) + 'px'); 

或刚刚起飞的领先字符串。

('top', contentheight + 44 + 'px'); 
1

尝试

if(ipadmenuheight < contentheight).css('top', '' + (contentheight + 44) + 'px'); 

或最终

if(ipadmenuheight < contentheight).css('top', '' + (parseInt(contentheight, 10) + 44) + 'px'); 

如果contentHeight大的字符串。

+1

你可能想使用'parseInt(str,10)',否则你可能会得到奇怪的结果,比如'parseInt('010')=== 8''。 – pimvdb

+0

有效点,修复。 – usoban