D3:选择和更改外部 SVG? [英] D3: Select and alter external SVG?

查看:31
本文介绍了D3:选择和更改外部 SVG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Adob​​e Illustrator 中创建的嵌入(外部)SVG 中选择和更改元素?

Is it possible to select and alter elements in an embedded (external) SVG , created in Adobe Illustrator?

html:

<object data="circles.svg" type="image/svg+xml" id="circles"></object>

circles.svg:

circles.svg:

<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="100px" >
  <circle id="c_red" fill="#A00" stroke="#000" cx="40" cy="40" r="40"/>
  <circle id="c_grn" fill="#0A0" stroke="#000" cx="60" cy="60" r="40"/>
</svg>

d3 代码:

<script>
  var my_circles = d3.select("#circles svg").selectAll("circles");
  my_circles.attr("fill", "black");
</script>

否则,我愿意接受其他方法.例如,像这样的东西可能适用于选择(它确实定位了 SVG):

Otherwise, I'm open to other ways of doing this. For example, something like this might work to select (which does indeed locate the SVG):

var svg = document.getElementById('circles');

但是如何在 D3 中解析和更改?额外问题:调试 D3 选择器的最佳方式?

But how to then parse and alter in D3? Bonus question: best way to debug D3 selectors?

推荐答案

这实际上是一个令人讨厌的情况,因为您不能直接在嵌入式文档上使用 DOM 选择器.原则上,您需要的选择器是 "#circles > circle",但在这种情况下这不起作用.所以你需要一些相当丑陋的东西

This is actually a nasty case, because you can't use DOM selectors directly on embedded documents. In principle, the selector you need is "#circles > circle", but this won't work in this case. So you need something rather ugly like

var my_circles = d3.select(document.getElementById("circles").contentDocument)
                   .selectAll("circle");

我发现 Javascript 控制台对于调试选择器非常有用.只需输入您要测试的内容,然后查看是否返回您要的内容.

I find the Javascript console quite useful for debugging selectors. Just type in what you want to test and see if the things you want are returned.

问题是上面的代码只有在对象加载后才有效.即使使用 JQuery 的 .ready() 之类的东西也不足以确保这一点.一个快速而肮脏的解决方案是反复检查元素是否存在,直到它们存在:

The problem is that the above code only works once the object has been loaded. Even using something like JQuery's .ready() won't be sufficient to ensure that. A quick and dirty solution is to repeatedly check whether the elements are present until they are:

function changeColor() {
  var sel = d3.select(document.getElementById("circles").contentDocument)
              .selectAll("circle");
  if(sel.empty()) {
    setTimeout(changeColor, 100);
  } else {
    sel.attr("fill", "black");
  }
}
changeColor();

完整示例此处.

这篇关于D3:选择和更改外部 SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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