获得CSS百分比宽度返回像素.我需要的百分比与.css文件或与属性内联的CSS样式中设置的百分比相同



我已经将样式设置为%like:

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

,它返回使用JQuery的css()函数

中的像素中的结果
$(document).ready(function(){
  var css = $("#somediv").css('width');
  console.log(css);
});

我已经创建了自己的jQuery插件来解决它

(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));

如何:

$(document).ready(function(){
    var css = $('#somediv').smartcss('width');
    console.log(css);
    });

最新更新