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

前端 未结 15 1671
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    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! :)

提交回复
热议问题