get CSS rule's percentage value in jQuery

后端 未结 12 1345
一个人的身影
一个人的身影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:36

    This is most definitely possible!

    You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.

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

    See my example.

    Now... I wonder if I'm first to discover this hack:)

    Update:

    One-liner

    element.clone().appendTo('body').wrap('
    ').css('width');

    It will leave behind a hidden element before the tag, which you may want to .remove().

    See an example of one-liner.

    I'm open to better ideas!

提交回复
热议问题