【问题标题】:apply negative value with variable using .css with jquery使用 .css 和 jquery 对变量应用负值
【发布时间】:2014-02-22 14:38:40
【问题描述】:

我有一个语法问题,因为我想做一些非常简单的事情。使用.css 将负值应用于变量。

这里有代码:

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

你怎么写正确?

【问题讨论】:

  • 你不用(0-(figureImageWidth/2))-figureImageWidth/2就可以了。
  • 如果你不知道figureImageMarginLeft-ve+ve,那么你可以这样做,-Math.abs(figureImageMarginLeft) 总是得到负数.
  • @AshishKumar 这工作得很好,但我想知道将来如何在需要时将这个负值应用于 .css 字段。
  • @AshishKumar Steve Robinson 的答案是正确的,但我想知道哪种方法更适合速度质量或最佳实践
  • 在 jQuery 中,您不需要将 px 指定为 .css().animate().height() 等的单位。

标签: javascript jquery css margin negative-number


【解决方案1】:

是的,当然。如果你这样做,

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

元素将获得规则:margin-left: -100px

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如果我这样做,则根本不会显示该值。所以这段代码根本不能让它工作。您还有其他意见吗?
    【解决方案3】:

    你可以这样做:

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

    Fiddle

    【讨论】:

      【解决方案4】:

      这样就可以解决问题(会使正值变为负值,负值变为正值):

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

      或者,如果您希望它始终为负数:

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

      总是积极的:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-27
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2016-10-26
        相关资源
        最近更新 更多