javascript 如何为 SVG 更改或添加 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8027390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:01:58  来源:igfitidea点击:

How to change or add an ID to a SVG?

javascriptjquerydomraphael

提问by 3logy

I have a SVG create with Raphael 2.0 which look like this :

我有一个使用 Raphael 2.0 创建的 SVG,如下所示:

<div class="stave">
<svg height="342" version="1.1" width="512" xmlns="http://www.w3.org/2000/svg"
style="overflow: hidden; position: relative;" viewBox="0 410 1300 80"
preserveAspectRatio="meet">
........
</svg>
</div>

i just want to set an ID to the svg tag! How can i do it? JQUERY or RAPHAEL 2.0? i have see many answers but none works for me.

我只想为 svg 标签设置一个 ID!我该怎么做?JQUERY 还是 RAPHAEL 2.0?我看到了很多答案,但没有一个对我有用。

Thank you for helping

谢谢你的帮忙

采纳答案by enloz

With jQuery you can use element selectorand :nth-child().

使用 jQuery,您可以使用元素选择器:nth-child()

Something like this: (jsFiddle)

像这样:(jsFiddle

<div class="frame">
    <div>div1</div>
    <div>div2</div>
    <div>div3</div>
</div>
<script type="text/javascript">
    $('div').css({'font-weight':'bold'});
    $('.frame div:nth-child(2)').attr("id","newId");
    $('#newId').css({'color':'#f30'})
</script>

Of course, in your case, selector would be $('svg')

当然,在您的情况下,选择器将是 $('svg')

回答by Some Guy

document.getElementsByTagName('svg')[0].id = 'svg_id';

That should work if you have only one SVG tag on your page and if you've called it after having created the tag using Raphael.

如果您的页面上只有一个 SVG 标记,并且您在使用 Raphael 创建标记后调用了它,那么这应该有效。

If you haven't created the tag using Raphael, you can just use something like this:

如果您还没有使用 Raphael 创建标签,您可以使用以下内容:

<svg id='svg_id'></svg>

Along with the other attributes, of course.

当然,还有其他属性。

回答by ludeq

var paper=Raphael(0, 0, 342, 512)
paper.canvas.id='id_svg1'