How to get just numeric part of CSS property with jQuery?

前端 未结 15 1641
悲哀的现实
悲哀的现实 2020-11-28 18:53

I need to do a numeric calculation based on CSS properties. However, when I use this to get info:

$(this).css(\'marginBottom\')

it returns

相关标签:
15条回答
  • 2020-11-28 19:49

    parseint will truncate any decimal values (e.g. 1.5em gives 1).

    Try a replace function with regex e.g.

    $this.css('marginBottom').replace(/([\d.]+)(px|pt|em|%)/,'$1');
    
    0 讨论(0)
  • 2020-11-28 19:58

    With the replace method, your css value is a string, and not a number.

    This method is more clean, simple, and returns a number :

    parseFloat($(this).css('marginBottom'));
    
    0 讨论(0)
  • 2020-11-28 19:58

    I use a simple jQuery plugin to return the numeric value of any single CSS property.

    It applies parseFloat to the value returned by jQuery's default css method.

    Plugin Definition:

    $.fn.cssNum = function(){
      return parseFloat($.fn.css.apply(this,arguments));
    }
    

    Usage:

    var element = $('.selector-class');
    var numericWidth = element.cssNum('width') * 10 + 'px';
    element.css('width', numericWidth);
    
    0 讨论(0)
提交回复
热议问题