简体   繁体   English

如何使用Snap.svg更新SVG文本元素?

[英]How do I update an SVG text element using Snap.svg?

I'm using Snap.svg to load an SVG image and add text elements to it. 我正在使用Snap.svg加载SVG图像并向其添加文本元素。 However, I need to be able to update the text elements as the page loads. 但是,我需要能够在页面加载时更新文本元素。

Right now, I'm doing something like this: 现在,我正在做这样的事情:

var svg = Snap("#selector");
var text;
Snap.load(path_to_file, function(f) {
    svg.append(f);
    var g = svg.select("g");
    text = g.text(x_pos, y_pos, label);
}

Let's say I want to update the text later, how do I do this? 假设我想稍后更新文本,我该怎么做? I am guaranteed to update the text object after it's been created after calling load . 我保证在调用load后创建text对象后更新它。

The only way I've managed to modify the text is by setting an id to the element and then doing it with jQuery like this: 我设法修改文本的唯一方法是为元素设置一个id ,然后使用jQuery这样做:

self.selector.find("#my_id")[0].textContent = "New text";

However, this feels really wrong and I think I might just be missing something with the Snap API. 但是,这感觉非常错误,我想我可能只是缺少使用Snap API的东西。

I think it should be as simple as 我认为应该这么简单

text.attr({ text: 'my new text'});

so 所以

setTimeout( function() { text.attr({ text: 'my new text'}) }, 2000 );

would test it 会测试它

Another way, you can directly get a reference of DOM node using Element.node , so you can mess around 另一种方法,你可以使用Element.node直接获取DOM节点的引用,这样你就可以搞砸了

text.node.textContent = "New text";
text.node.innerHTML = "New text";
text.node.innerHTML = 'a<tspan dy="5">2</tspan>'

用jquery

$(s.select('#id').node).text('new text');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM