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

前端 未结 15 1640
悲哀的现实
悲哀的现实 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:32

    You can implement this very simple jQuery plugin:

    Plugin Definition:

    (function($) {
       $.fn.cssValue = function(p) {
          var result;
          return isNaN(result = parseFloat(this.css(p))) ? 0 : result;
       };
    })(jQuery);
    

    It is resistant to NaN values that may occur in old IE version (will return 0 instead)

    Usage:

    $(this).cssValue('marginBottom');
    

    Enjoy! :)

    0 讨论(0)
  • 2020-11-28 19:33

    For improving accepted answer use this:

    Number($(this).css('marginBottom').replace(/[^-\d\.]/g, ''));
    
    0 讨论(0)
  • 2020-11-28 19:34
    parseInt($(this).css('marginBottom'), 10);
    

    parseInt will automatically ignore the units.

    For example:

    var marginBottom = "10px";
    marginBottom = parseInt(marginBottom, 10);
    alert(marginBottom); // alerts: 10
    
    0 讨论(0)
  • 2020-11-28 19:36

    Let us assume you have a margin-bottom property set to 20px / 20% / 20em. To get the value as a number there are two options:

    Option 1:

    parseInt($('#some_DOM_element_ID').css('margin-bottom'), 10);
    

    The parseInt() function parses a string and returns an integer. Don't change the 10 found in the above function (known as a "radix") unless you know what you are doing.

    Example Output will be: 20 (if margin-bottom set in px) for % and em it will output the relative number based on current Parent Element / Font size.

    Option 2 (I personally prefer this option)

    parseFloat($('#some_DOM_element_ID').css('margin-bottom'));
    

    Example Output will be: 20 (if margin-bottom set in px) for % and em it will output the relative number based on current Parent Element / Font size.

    The parseFloat() function parses a string and returns a floating point number.

    The parseFloat() function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

    The advantage of Option 2 is that if you get decimal numbers returned (e.g. 20.32322px) you will get the number returned with the values behind the decimal point. Useful if you need specific numbers returned, for example if your margin-bottom is set in em or %

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

    Even if marginBottom defined in em, the value inside of parseFloat above will be in px, as it's a calculated CSS property.

    0 讨论(0)
  • 2020-11-28 19:38

    Should remove units while preserving decimals.

    var regExp = new RegExp("[a-z][A-Z]","g");
    parseFloat($(this).css("property").replace(regExp, ""));
    
    0 讨论(0)
提交回复
热议问题