2014-01-30 36 views
1

我有一個語法問題,因爲我想做一件很簡單的事情。使用.css將負值應用於變量。應用負值與變量使用.css與jquery

這裏喲有代碼:

var figureImage = $('.js-image-centering'); 
var figureImageHeight = figureImage.height(); 
var figureImageWidth = figureImage.width(); 
var figureImageMarginLeft = (0-(figureImageWidth/2)); 
var figureImageMarginTop = (0-(figureImageHeight/2)); 

figureImage.css('margin-left', figureImageMarginLeft); 
figureImage.css('margin-top', figureImageMarginTop); 

我想忘記figureImageMarginLeftfigureImageMarginTop。那麼,它有可能是這樣的嗎?

figureImage.css('margin-left', -figureImageMarginLeft); 

你如何正確地寫呢?

+1

你不需要做'(0-(figureImageWidth/2 ))',''-figureImageWidth/2'很好。 –

+0

如果你不知道'figureImageMarginLeft'是** - ve **還是** + ve **,那麼你可以這樣做:'-Math.abs(figureImageMarginLeft)'總是得到負數。 –

+0

@AshishKumar這工作完美,但我想知道未來如何將這個負值應用於.css字段,如果我需要它。 –

回答

4

是的絕對。如果你這樣做,

var a = 100; 
$(".stuff").css("margin-left",-a) 

元素會得到規則:margin-left: -100px

0

figureImage.css('margin-left', "-" + figureImageMarginLeft + 'px');怎麼樣?

+0

如果我這樣做,則根本不顯示該值。所以這段代碼根本就沒有成功。你有其他的意見嗎? –

0

你可以只是這樣做:

var mL = -30; 
$("div").css("marginLeft", mL + "px"); 

Fiddle

0

這將這樣的伎倆(將作出積極的值爲負值和負值陽性):

figureImage.css('margin-left', -figureImageMarginLeft+"px"); 

,或者,如果你希望它是始終爲負:

figureImage.css('margin-left', -Math.abs(figureImageMarginLeft)+"px"); 

總是positiv:

figureImage.css('margin-left', Math.abs(figureImageMarginLeft)+"px"); 

例如:http://jsfiddle.net/rN3cw/