在Snap.svg图形上设置ID属性 [英] Set ID attribute on a Snap.svg graphic

查看:628
本文介绍了在Snap.svg图形上设置ID属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Snap.svg API,我需要在CSS中选择三个图形用于样式设置。因此,为了区分它们,我需要给它们一个ID或类名。

I'm using Snap.svg API and I have three graphics that I need to select in my CSS for styling purposes. Thus, to distinguish between them, I need to give them an ID or class name.

这是我创建元素的方式:

var draw = Snap(100, 75);
c = draw.polyline(0,0, 50,75, 100,0, 0,0);
c.attr({
    fill: "black"
});

这是我得到的结果:

<svg height="75" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg">
    <polyline points="0,0,50,75,100,0,0,0" style="" fill="#000000"></polyline>
</svg>

这就是我需要的结果:

<svg id="graphic_1" height="75" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg">
    <polyline points="0,0,50,75,100,0,0,0" style="" fill="#000000"></polyline>
</svg>


推荐答案

< h1>更新

我在GitHub上提出了一个问题,看起来这将是在下一个版本中修复。目前,在开发分支上,您可以使用 Element.attr

Update

I raised an issue on GitHub and it looks like this will be fixed in the next release. For now, on the development branch, you can use Element.attr:

var draw = Snap(100, 75);
draw.attr({ id: 'graphic_1' });

我将在下面留下原始答案,因为:

I'm leaving the original answer below because:


  1. 在撰写本文时,这在master(发布)版本中不起作用;和

  2. 所描述的直接访问底层DOM节点的技术可能对将来的其他人或使用旧版Snap.svg的技术有用。






没有记录,但内部Snap.svg将DOM节点存储在名为 node <的属性中/ code>。因此,您可以像这样设置画布的ID:


It's not documented, but internally Snap.svg stores the DOM node in a property called node. Thus, you can set the ID of the canvas like so:

draw.node.id = 'graphic_1';

或者,如果您希望避免使用未记录的技术,可以创建一个ID为您的元素想首先并直接使用它:

Alternatively, if you would prefer to avoid undocumented techniques, you could create an element with the ID that you want first and use that directly:

<svg id="graphic_1" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="75"></svg>



var draw = Snap("#graphic_1");

这篇关于在Snap.svg图形上设置ID属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆