svg作为对象加载

时间:2017-02-15 23:22:50

标签: object svg draw

嗨,我对js很陌生,我不太了解svg应该如何工作。

我已经生成了一个我想在网页中使用的svg文件。该文件非常大,我不想将其粘贴到内联中,因为我希望能够将其替换为另一个。我还需要访问它的元素,因此,AFAIK,唯一的选择是将其加载为<object>而不是<img>

然而,当我以这种方式加载它时,我发现了很多警告。

当我想在对象上添加更多svg图层时,其中一个是绘图顺序。

如果按此顺序编写元素

blue circle svg
object
green circle svg

我看到对象上方的蓝色圆圈和对象下方的绿色圆圈(就像它被对象推动一样)。我希望看到我在背景中绘制的第一个元素和前面的最后一个元素。

<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<circle id = "AGV01R" cx = "140" cy="100" r = "20" fill = "blue"></circle>
</svg>

<object type = "image/svg+xml" data="http://upload.wikimedia.org/wikipedia/commons/5/57/Weakness_of_Turing_test_1.svg" class="plano" id="plano"></object>

<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<circle id = "AGV02R" cx = "140" cy="100" r = "15" fill = "green"></circle>
</svg>

http://codepen.io/mrcasty/pen/egXaBj

1 个答案:

答案 0 :(得分:0)

如果您想要放置三个HTML元素,使它们堆叠在彼此的顶部(上方),最好的解决方案是将它们包装在一个也位于&#34;定位的容器中。我的意思是它的风格有position属性。

通常人们会使用position: relative,因为这不会影响容器元素的正常流量位置。

&#13;
&#13;
.container {
  position: relative;
}

.container svg,
.container object {
    position:absolute;
}
&#13;
<div class="container">

  <svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
    <circle id = "AGV01R" cx = "140" cy="100" r = "20" fill = "blue"></circle>
  </svg>

  <object type = "image/svg+xml" data="http://upload.wikimedia.org/wikipedia/commons/5/57/Weakness_of_Turing_test_1.svg" class="plano" id="plano">
</object>

  <svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
    <circle id = "AGV02R" cx = "140" cy="100" r = "15" fill = "green"></circle>
  </svg>
  
</div>
&#13;
&#13;
&#13;

关于你的另一个问题。如果您想操纵SVG的DOM,您必须内联它,或使用<object>。别无选择。

有些人所做的是使用在页面加载上运行的脚本来加载外部文件并自动内联它们。正如@ andrew-willems所建议的那样:

Include SVG files with HTML, and still be able to apply styles to them?