代码之家  ›  专栏  ›  技术社区  ›  montrealist

在jquery中获取css规则的百分比值

  •  96
  • montrealist  · 技术社区  · 17 年前

    假设规则如下:

    .largeField {
        width: 65%;
    }
    

    有没有办法让“65%”,而不是像素值?

    谢谢。

    编辑: 不幸的是,在我的例子中,使用DOM方法是不可靠的,因为我有一个导入其他样式表的样式表,因此 CSS规则 参数的结尾是 无效的 未定义 价值。

    然而,这种方法可以在最简单的情况下工作(一个样式表,在 文档的标签)。

    13 回复  |  直到 8 年前
        1
  •  48
  •   Adam Lassek    17 年前

    恐怕没有内置的方式。你可以这样做:

    var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
    
        2
  •  110
  •   redexp    14 年前

    最简单的方法

    $('.largeField')[0].style.width
    
    // >>> "65%"
    
        3
  •  82
  •   Timofey Drozhzhin    11 年前

    这绝对是可能的!

    必须首先隐藏()父元素。这将阻止javascript计算子元素的像素。

    $('.parent').hide();
    var width = $('.child').width();
    $('.parent').show();
    alert(width);
    

    看到我 example .

    现在。。。我想知道我是否是第一个发现这个黑客的人:)

    更新:

    一班轮

    element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
    

    它将在 </body> 标签,您可能需要 .remove() .

    见一 example of one-liner .

    我乐于接受更好的想法!

        4
  •  44
  •   maxgalbu    12 年前

    您可以访问 document.styleSheets 对象:

    <style type="text/css">
        .largeField {
            width: 65%;
        }
    </style>
    <script type="text/javascript">
        var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
        for (var i=0; i < rules.length; i++) {
            var rule = rules[i];
            if (rule.selectorText.toLowerCase() == ".largefield") {
                alert(rule.style.getPropertyValue("width"));
            }
        }
    </script>
    
        5
  •  17
  •   ddanone    10 年前

    晚了,但对于新用户,请尝试此操作 如果CSS样式包含百分比 :

    $element.prop('style')['width'];
    
        6
  •  8
  •   Leonard Pauli    13 年前

    基于Adams Answer的jQuery插件:

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

    将返回“65%”。仅当您喜欢if(width='65%')时返回四舍五入的数字才能更好地工作。如果你直接用亚当斯的答案,那就没用了(我得到了64.93288590604027)。:)

        7
  •  3
  •   Gregory Magarshak    10 年前

    基于Timofey出色而令人惊讶的解决方案,这里有一个纯JavaScript实现:

    function cssDimensions(element)
      var cn = element.cloneNode();
      var div = document.createElement('div');
      div.appendChild(cn);
      div.style.display = 'none';
      document.body.appendChild(div);
      var cs = window.getComputedStyle
        ? getComputedStyle(cn, null)
        : cn.currentStyle;
      var ret = { width: cs.width, height: cs.height };
      document.body.removeChild(div);
      return ret;
    }
    

    希望这对某人有帮助。

        8
  •  1
  •   Community Mohan Dere    9 年前

    我也有类似的问题 Getting values of global stylesheet in jQuery 最终我想出了 same solution as above .

    只是想把这两个问题联系起来,这样其他人就可以从后面的发现中获益。

        9
  •  0
  •   wheresrhys    17 年前

    您可以将需要通过jquery访问的样式放在以下任一位置:

    1. 文件的主管直接
    2. 在include中,然后将哪个服务器端脚本放在头中

    然后应该可以(尽管不一定容易)编写一个JS函数来解析文档头中样式标记中的所有内容,并返回所需的值。

        10
  •  0
  •   user267867    16 年前

    可以使用css(width)函数返回元素的当前宽度。

    IE.

    var myWidth = $("#myElement").css("width");
    

    参见: http://api.jquery.com/width/ http://api.jquery.com/css/

        11
  •  0
  •   Desarrollo BlueSoft    11 年前

    我正在重写用户1491819的评论作为答案,并增加了一些改进(我不能评论,因为声誉不好)。

    用户1491819创建了这个非常有用的函数:

    function getCssWidth(childSelector) {
      return jQuery(childSelector).parent().clone().hide().find(childSelector).width();
    }
    

    但是这个函数返回没有单位的像素数或百分比,因此您需要猜测哪个是。 对于不猜测,您可以使用css(“width”),它也将返回单位。 因此,获取单位值的函数应该是:

    function getCssWidth(childSelector) {
      return jQuery(childSelector).parent().clone().hide().find(childSelector).css('width');
    }
    
        12
  •  0
  •   B T    9 年前

    jquery中没有任何内容,甚至在javascript中也没有直接的内容。我接受了Timofey的答案并使用它运行,创建了这个函数,它可以获得您想要的任何属性:

    // gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
    // domNode - the node to get properties for 
    // properties - Can be a single property to fetch or an array of properties to fetch
    function getFinalStyle(domNode, properties) {
        if(!(properties instanceof Array)) properties = [properties]
    
        var parent = domNode.parentNode
        if(parent) {
            var originalDisplay = parent.style.display
            parent.style.display = 'none'
        }
        var computedStyles = getComputedStyle(domNode)
    
        var result = {}
        properties.forEach(function(prop) {
            result[prop] = computedStyles[prop]
        })
    
        if(parent) {
            parent.style.display = originalDisplay
        }
    
        return result
    }
    
        13
  •  0
  •   Clean Code Studio    8 年前

    使用交叉乘法从像素转换为百分比 .

    公式设置:

    1) (element_width_pixels/parent_width_pixels)=(element_width_percentage/100)

    2.)元素宽度百分比= (100*元素宽度像素)/父元素宽度像素

    实际代码:

    <script>
    
       var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
    
    </script>