外部加载的SVG文件的元素id

ids of elements of externally loaded svg file

本文关键字:元素 id 文件 SVG 加载 外部      更新时间:2023-09-26

我已经将svg文件加载到"g"中,如下(canvas是基于Snap-svg的):

var _i = new Image();
_i.src = 'svgFile.svg';
$(_i).load(function () {
    Snap.load(src, function(f){
    _imagen = canvas.g(f.select('*'));
    canvas.append(_imagen);
    });

svg文件(svgFile.svg)包含(除其他外):

<path id="letterN" fill="#FCEA0D" stroke="#000000" stroke-miterlimit="10" d="M606,538 ... z"/>

外部文件添加得很好,我可以在页面中看到它。但是当我在控制台中查找元素(路径)时,我看到它的id ="Shyphnh2b1fg"。这发生在文件中的所有svg元素上。为什么id会改变?更重要的是,怎样才能避免呢?任何帮助将非常感激!

这实际上不是SVG id,所以我怀疑您看错了。

Snap添加了自己的id,如果您查看Chrome Console日志之类的东西,并执行Console .log(someElement),您将看到对象将具有id,但底层SVG元素(可通过someElement访问)。attr或someElement.node),然后显示实际的SVG,单击"attributes",您将看到"id"在那里有原始的。

基本上,你看的是Snap实例Id,而不是svg元素Id它们是分开的东西。下面的代码应该有点帮助

console.log( el );
console.log( el.id ); // snap id, don't often need to use this
console.log( el.attr('id') ); // use this normally, snap access to underlying svg id
console.log( el.node.attributes.id.value ); // actual reference to svg id, should be the same as attr('id')