简体   繁体   English

将.css与jquery一起对变量应用负值

[英]apply negative value with variable using .css with jquery

I have a syntax issue as I want to do something quite simple. 我有一个语法问题,因为我想做一些非常简单的事情。 Apply a negative value to a variable using .css . 使用.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 . 我想忘记figureImageMarginLeftfigureImageMarginTop 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 元素将获得规则: margin-left: -100px

What about figureImage.css('margin-left', "-" + figureImageMarginLeft + 'px'); 那么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): 这样就可以解决问题(将正值设为负,而负值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/ 例如: http//jsfiddle.net/rN3cw/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM