【问题标题】:Can't append simple svg to body element无法将简单的 svg 附加到正文元素
【发布时间】:2021-10-30 15:16:23
【问题描述】:

我知道这是一个超级简单的问题。但我显然错过了一些非常明显的东西。 我只想用 D3 创建一个 svg 元素并在我的页面上看到它。 我的index.html看起来像这样:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="node_modules/d3/dist/d3.min.js"></script>
        <script src="selections.js"></script>
        <link rel="stylesheet" href="style.css">
        <title>D3 Selections</title>
    </head>

    <body>
    </body>

</html>

而我的selections.js 看起来像这样:

console.log("This appears...")

w = window.innerWidth
h = window.innerHeight

// // make the svg

const svg = d3.select("body")
    .append("svg")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg")

第一个console.log() 在控制台中仍然可见。但我看不到svg。我知道我错过了一些非常清晰的东西,但我现在看不到它:/

【问题讨论】:

  • 您可以按照当前答案的建议进行操作,或者您可以简单地将selections.js 移动到&lt;body&gt; 的底部,然后D3 将有一些东西可以选择并附加SVG。跨度>
  • 非常感谢!这是D3常见的事情吗?我想当你的 D3 代码变大一点时,将它全部放在脚本标签中可能会有点烦人?!
  • 不,与 D3 无关,这是浏览器的工作方式,看这里:stackoverflow.com/q/17106462/5768908
  • 关于第二个问题,使用外部脚本是个好主意。

标签: javascript svg d3.js


【解决方案1】:

我不太了解 d3.js,但您可能应该等待 DOM 加载:

console.log("This appears...");

w = window.innerWidth;
h = window.innerHeight;

document.addEventListener('DOMContentLoaded', e => {
  // // make the svg
  const svg = d3.select("body")
    .append("svg")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg");
});

【讨论】:

  • 非常感谢,这工作:)!当我可以在 JS 中做什么时,我真的很困惑
  • @Lenn addEventListener() 更灵活。如果您将某些内容分配给window.onload 更多次,它们将相互覆盖。使用事件监听器,您可以拥有多个。
猜你喜欢
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多