get CSS rule's percentage value in jQuery

后端 未结 12 1346
一个人的身影
一个人的身影 2020-11-22 08:22

Let\'s say the rule is as follows:

.largeField {
    width: 65%;
}

Is there a way to get \'65%\' back somehow, and not the pixel value?

12条回答
  •  终归单人心
    2020-11-22 08:38

    A jQuery plugin based on Adams answer:

    (function ($) {
    
        $.fn.getWidthInPercent = function () {
            var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
            return Math.round(100*width)+'%';
        };
    
    })(jQuery);
    
    $('body').html($('.largeField').getWidthInPercent());​​​​​
    

    Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)

提交回复
热议问题