Omn*_*ous 0 html javascript svg d3.js
这个问题更多是为了满足我自己的好奇心,而不是其他任何事情。我想知道如何使用 d3 选择已经存在于 HTML 文档正文中的 SVG 元素,而无需先使用 d3 创建该 SVG 元素。我希望以下代码段可以工作,但它不起作用,这让我感到非常沮丧。
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js">
</script>
<script type="text/javascript">
// If the below is changed to append instead of select it works
// but what if I don't want to create the SVG using d3
var svg = d3.select("body").select("svg")
var circle = svg.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 20)
</script>
<style>
</style>
</head>
<body>
<svg>
</svg>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
所以这是一个经典的 JavaScript 问题。它无法正常工作,因为页面元素尚未完成加载。解决方法是将 d3 代码从头部移动到结束正文标记之前。
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js">
</script>
<style>
</style>
</head>
<body>
<svg>
</svg>
<script type="text/javascript">
// If the below is changed to append instead of select it works
// but what if I don't want to create the SVG using d3
var svg = d3.select("body").select("svg");
var circle = svg.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 20)
.style("color", "green");
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2539 次 |
| 最近记录: |