Padding or margin value in pixels as integer using jQuery

后端 未结 14 2212
陌清茗
陌清茗 2020-11-28 02:40

jQuery has height() en width() functions that returns the height or width in pixels as integer...

How can I get a padding or margin value of an element in p

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 03:26

    Not to necro but I made this which can determine pixels based on a variety of values:

    $.fn.extend({
      pixels: function (property, base) {
        var value = $(this).css(property);
        var original = value;
        var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
          ? $(this).parent().outerWidth()
          : $(this).parent().outerHeight();
    
        // EM Conversion Factor
        base = base || 16;
    
        if (value == 'auto' || value == 'inherit') 
            return outer || 0;
    
        value = value.replace('rem', '');
        value = value.replace('em', '');
    
        if (value !== original) {
           value = parseFloat(value);
           return value ? base * value : 0;
        }
    
        value = value.replace('pt', '');
    
        if (value !== original) {
           value = parseFloat(value);
           return value ? value * 1.333333 : 0; // 1pt = 1.333px
        }
    
        value = value.replace('%', '');
    
        if (value !== original) {
          value = parseFloat(value);
          return value ? (outer * value / 100) : 0;
        }
    
        value = value.replace('px', '');
        return parseFloat(value) || 0;
      }
    });
    

    This way, we take into account for sizing, and auto / inherit.

提交回复
热议问题