javascript 使用 D3 将 SVG 画布附加到身体以外的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13865606/
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 20:00:40  来源:igfitidea点击:

Append SVG canvas to element other than body using D3

javascripthtmld3.jssvg

提问by Gilman

Is it possible to append an SVG canvas to an element other than <body>using D3.js if the script is not inside that element?

<body>如果脚本不在该元素内,是否可以将 SVG 画布附加到使用 D3.js以外的元素?

For example, the code below does not work:

例如,下面的代码不起作用:

<html>
<body>
<script src="../../d3.v2.js"></script>
<script>
    var vis = d3.select("#container")
        .append("svg:svg")
          .attr("width",w)
          .attr("height",h);
</script>

<div id="container"></div>

</body>

All examples I have seen use d3.select("body").append....but clearly we don't always want to append the canvas immediately to the body.

我见过的所有示例都使用过,d3.select("body").append....但显然我们并不总是希望将画布立即附加到正文中。

I found that if the <script>is inside the container div then I can use d3.select("#container")but it seems strange to me that I would have to include my script inside of the specific container(s) where I want the canvas.

我发现如果<script>它在容器 div 内,那么我可以使用,d3.select("#container")但对我来说似乎很奇怪,我必须将我的脚本包含在我想要画布的特定容器中。

回答by Zikes

You're trying to select #containerbefore it exists. You'll need to put your code in an onloador move the script below #containerin the page.

您正在尝试#container在它存在之前进行选择。您需要将代码放入页面中onload或将脚本移至#container页面下方。