首页 > 解决方案 > 将css宽度作为数字而不是百分比

问题描述

在我的代码的这个简化版本中,我试图将 css 宽度提取为没有附加百分比的数字。研究一个解决方案,我发现了这个:获取一个没有“px”的样式值的数字;解决问题的后缀。但是,在尝试重现相同的结果时,我得到了

barSize:  NaN

代替

barSize: 90;

更新:这个问题不是在问如何获取属性

document.querySelector('.defaultBar').style.width

这使:

barSize: 90%

但是如何在没有后缀的情况下获得属性

parseInt(document.querySelector('.defaultBar').style.width, 10);

这应该给:barSize:90

没有%后缀,而是给出NaN

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <style>
    .defaultBar {
      background-color: green;
      height: 4px;
      width: 90%;
    }
  </style>
</head>

<body>
  <div class="defaultBar"></div>

  <script>
    const barSize = parseInt(document.querySelector('.defaultBar').style.width, 10);
    console.log("barSize: ", barSize);
  </script>
</body>

</html>

标签: javascripthtmlcss

解决方案


推荐阅读