get CSS rule's percentage value in jQuery

后端 未结 12 1462
一个人的身影
一个人的身影 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:30

    Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:

    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;
    }
    

    Hope it's helpful to someone.

提交回复
热议问题