获取带有单位的css

获取带有单位的css

This question already has answers here:
Get element CSS property (width/height) value as it was set (in percent/em/px/etc)

(5个答案)


4年前关闭。




我的代码是这样的:
#image_1 {
   position: absolute;
   top: 3vw;
}

我的尝试:
http://jsfiddle.net/z8k6t3fb/1/

我想得到“3vw”

是否可以 ?

最佳答案

您可以迭代document.styleSheets.cssRules,如果.selectorText与元素选择器匹配,请从.style属性中选择规则

window.onload = function() {
  var element = document.getElementById("image_1");
  var prop = "top";
  var styles = document.styleSheets;
  for (var j = 0; j < styles.length; j++) {
    var rules = document.styleSheets[j].cssRules;
    for (var i = 0; i < rules.length; i++) {
      if (rules[i].selectorText === "#" + element.id) {
        console.log(rules[i].style[prop])
      }
    }
  }
}
#image_1 {
  position: absolute;
  top: 3vw;
}
<div id="image_1">hello</div>

关于javascript:获取带有单位的css prop值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41055047/

10-08 22:26