D3: Select and alter external SVG?

后端 未结 1 1709
再見小時候
再見小時候 2020-12-19 10:46

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

html:



        
                      
相关标签:
1条回答
  • 2020-12-19 11:35

    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");
    

    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.

    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();
    

    Full example here.

    0 讨论(0)
提交回复
热议问题