2011-10-02 25 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