javascript - 在 JS 中设置没有单位的 CSS 值
问题描述
我正在尝试为 SVG 设置动画stroke-dashoffset
并stroke-dasharray
制作“绘图”效果。设置这些值时,单位需要与 SVGwidth
和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 剥离任何单位。
根据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>
推荐阅读
- python - boto2 get_key() 在已知键上返回 None
- typescript - 带有 SonarJS 的声纳扫描仪无法解析打字稿
- yocto - BitBake 将 tmux 包添加到图像
- vuetify.js - vuetify 中的 xs 断点无法正常工作
- python - 从带有条件的 for 循环中动态创建大量列表
- c# - 有什么方法可以确定实体框架 6.3 中正在编辑哪些实体
- python - 用二维坐标之间的距离填充一个 numpy 零数组
- keras - tf.keras 如何保存 ModelCheckPoint 对象
- http - http2:收到 GOAWAY [FrameHeader GOAWAY len=8],开始正常关机
- sql - 如何使用 CTE 删除 SQLite 中的重复列 - 错误