首页 > 解决方案 > 在 JS 中设置没有单位的 CSS 值

问题描述

我正在尝试为 SVG 设置动画stroke-dashoffsetstroke-dasharray制作“绘图”效果。设置这些值时,单位需要与 SVGwidthheightHTML 属性相关,在我的情况下,这些属性与文档上的实际大小分开设置(类似于 Canvas),因此没有单位。在 Chrome 中,这在 JavaScript 中运行良好,使用.style.strokeDashoffset.style.strokeDasharray. 然而,在 Firefox 中,我注意到这些无单位值会自动更正为像素单位。

我尝试在 JS 中使用单个样式变量(如上)和.style.cssText整体设置值,但无济于事。没有单位就不可能有值吗?

function pathAnimate(path) {
  var length = path.getTotalLength();
  path.style.strokeDasharray = length;
  path.getBoundingClientRect();
  if (path.style.strokeDashoffset == "0") {
    path.style.cssText = "stroke-dasharray: " + length + "; stroke-dashoffset: " + length + ";";
  } else {
    path.style.cssText = "stroke-dasharray: " + length + "; stroke-dashoffset: 0;";
  }
}

setInterval(() => {
  pathAnimate(document.querySelectorAll("svg path")[0]);
}, 1000)
svg path {
  stroke: #696969;
  stroke-width: 16;
  stroke-linecap: round;
  stroke-linejoin: round;
  fill: none;
  transition: all 0.5s ease-out;
}
<!DOCTYPE html>

<body>
  <svg width="371.43532" height="473.79655" viewbox="0 0 371.43532 473.79655">
    <path d="m 179.29563,388.2732 -0.71909,-227.11466 c -0.12011,-37.93426 41.87061,-39.6739 41.87061,0 v 189.77189 c 0,35.61587 43.29422,38.0718 43.76053,0 l 2.32434,-189.77189 c 0.8842,-72.190591 19.29427,-107.190071 63.3958,-155.7820307" />
    </svg>
</body>

注意:正如我在上面解释的那样,这个片段在 Chrome 中有效。

标签: javascriptcsssvg

解决方案


只需使用 parseFloat 剥离任何单位。

根据SVG 规范,省略的单位与像素相同。CSS 通常需要单位,即使 SVG 对这些事情更加放任。

1 px 单位被定义为等于 1 个用户单位。因此,“5px”的长度与“5”的长度相同。

function pathAnimate(path) {
  var length = path.getTotalLength();
  path.style.strokeDasharray = length;
  if (parseFloat(path.style.strokeDashoffset, 10) == 0) {
    path.style.cssText = "stroke-dasharray: " + length + "; stroke-dashoffset: " + length + ";";
  } else {
    path.style.cssText = "stroke-dasharray: " + length + "; stroke-dashoffset: 0;";
  }
}

setInterval(() => {
  pathAnimate(document.querySelectorAll("svg path")[0]);
}, 1000)
svg path {
  stroke: #696969;
  stroke-width: 16;
  stroke-linecap: round;
  stroke-linejoin: round;
  fill: none;
  transition: all 0.5s ease-out;
}
<!DOCTYPE html>

<body>
  <svg width="371.43532" height="473.79655" viewbox="0 0 371.43532 473.79655">
    <path d="m 179.29563,388.2732 -0.71909,-227.11466 c -0.12011,-37.93426 41.87061,-39.6739 41.87061,0 v 189.77189 c 0,35.61587 43.29422,38.0718 43.76053,0 l 2.32434,-189.77189 c 0.8842,-72.190591 19.29427,-107.190071 63.3958,-155.7820307" />
    </svg>
</body>


推荐阅读