문제

I have a syntax issue as I want to do something quite simple. Apply a negative value to a variable using .css.

Here yo have the code:

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);

I would like to forget about figureImageMarginLeft and figureImageMarginTop. So, its it possible to something like this?

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

How do you write it correctly?

도움이 되었습니까?

해결책

Yes Absolutely. If you do,

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

the element would get the rule: margin-left: -100px

다른 팁

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

You can just do this:

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

Fiddle

That will do the trick (will make positive values negative and negatives positiv):

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

or, if you want it to be always negative:

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

always positiv:

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

example: http://jsfiddle.net/rN3cw/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top