0

I've set styles in % like:

<style>
  #somediv {width:70%}
</style>
<div id="somediv"></div>

And it returns the result in pixels with jQuery's css() function

$(document).ready(function(){
  var css = $("#somediv").css('width');
  console.log(css);
});
lucasgabmoreno
  • 1,001
  • 1
  • 10
  • 18

1 Answers1

0

I've create my own jQuery plugin to solve it

(function ($) {
     $.fn.smartcss= function(i) {

var sel1 = this.selector;
var css1 = i;

// TOMAR DEL TAG STYLE Y/O DEL ARCHIVO .CSS
var css3;
$.each(document.styleSheets, function(sheetIndex, sheet) {
    $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
        var sel3 = rule.selectorText.toLowerCase().split(',');
        $.each(sel3,function(ii,jj){
            if(jj.trim() == sel1){
                var css2 = rule.style.getPropertyValue(css1);
                if(typeof(css2 != 'undefined') && (css2 != null)){
                    css3 = css2;

                    } //typeof
                } // jj==sel1
            }) //each
    }); // each
}); // each


// TOMAR DEL ATRIBUTO STYLE
var m2 = $(sel1).prop('style').cssText.split(';')
$.each(m2,function(ii,jj){
    var m22 = jj.split(':');
    if(m22[0].trim() == css1){
        css3 = m22[1].trim();
        }
    }) //each

// TOMAR DE JQUERY
if(typeof(css3) == 'undefined'){
    css3 = $(sel1).css(css1);
    }

return css3;

    };
 }(jQuery));

How to:

$(document).ready(function(){
    var css = $('#somediv').smartcss('width');
    console.log(css);
    });
lucasgabmoreno
  • 1,001
  • 1
  • 10
  • 18
  • 1
    You should post this code on http://codereview.stackexchange.com/. It looks alright, but the names of your variables, the comments and the indentation make this code too hard to read. For example, `css1` doesn't have anything to do with css1. The variables `ii` and `jj` are totally away from a `for` loop, where they are usually used (but without repeating). Other than that, the `m2` part is a complete waste of resources (use the `style` property in each element instead). – Ismael Miguel May 06 '15 at 18:37