<path> 从 HTML 中的 svg 路径获取元素



我正试图从html中的svg路径中获得svg路径字符串。假设我有一个这种格式的svg路径。

<path d="M 0 68.5 C -1.56977e-13 30.6685 184.011 -1.30814e-14 411 -3.92443e-14 C 637.989 -5.23258e-14 822 30.6685 822 68.5 C 822 106.332 637.989 137 411 137 C 184.011 137 -1.56977e-13 106.332 0 68.5 Z" fill-rule="evenodd" fill="none" stroke="none"></path>

如何获取path中的值标记,特别是内的值d属性。

有一种方法是通过一些基本的操作来获得它,比如获取M的索引并填充,但这不是一个很好的解决方案。

var htmlStr = elem.outerHTML;
var start = htmlStr.indexOf("M");
var end = htmlStr.indexOf("fill");
var str = htmlStr.substring(start, end);
str.replace(""", "");
str.trim();

谁能提出一些通用的解决方案吗?注意:path标签没有任何Id,我不能创建一个,因为它来自其他服务

你可以这样使用path的属性:

const pathId = document.getElementById("pathId");
const dValue = pathId.attributes["d"].value;
console.log(dValue);
<path id="pathId" d="M 0 68.5 C -1.56977e-13 30.6685 184.011 -1.30814e-14 411 -3.92443e-14 C 637.989 -5.23258e-14 822 30.6685 822 68.5 C 822 106.332 637.989 137 411 137 C 184.011 137 -1.56977e-13 106.332 0 68.5 Z" fill-rule="evenodd" fill="none" stroke="none"></path>

最新更新