我正在尝试为 SVG 的 stroke-dashoffset
和 stroke-dasharray
制作动画,以产生“绘图”效果。设置这些值时,单位需要相对于 SVG 的 width
和 height
HTML 属性,在我的例子中,这些属性与其在文档中的实际大小分开设置(类似于 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。
最佳答案
只需使用 parseFloat 去除任何单位。
根据 the SVG specification省略的单位与像素相同。 CSS 通常需要单位,即使 SVG 对此类事物更加自由放任。
One px unit is defined to be equal to one user unit. Thus, a length of "5px" is the same as a length of "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>
关于javascript - 在 JS 中设置没有单位的 CSS 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57761368/