gpt4 book ai didi

javascript - 使用 jquery 动态生成标记时不显示

转载 作者:行者123 更新时间:2023-11-30 12:57:10 27 4
gpt4 key购买 nike

我创建了一个标记以显示在线条元素的末尾。但我的问题是,当动态生成标记标签时,它不会显示在行尾。

我所做的是首先将 svg 附加到 html 主体。

var svg = d3.select('body').append("svg").attr("width", 300).attr("height", 300).attr("id", "cloud");  

然后我将标记附加到 svg。

$('svg').append('<defs><marker id="arrow" viewbox="0 -5 10 10" refX="18" refY="0"markerWidth="6" markerHeight="6" orient="auto"><path d="M0,-5L10,0L0,5Z"></marker> </defs>'); 

然后我将行附加到 svg,属性 marker-end 指向 svg 标记元素。

svg.append("g").selectAll("line.link")
.data(force.links())
.enter().append("line")
.attr("class", "link")
.attr("marker-end", "url(#arrow)");

标记不显示在行尾。这是 jsfiddle http://jsfiddle.net/2NJ25/2/ 中该代码的链接

但是当我使用 jquery 删除动态追加并在 html 中定义标记标签时,就像下面的代码一样,它在这里工作的链接是 http://jsfiddle.net/AqK4L/4/

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Cloud</title>
<script type="text/javascript" src="d3.v2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<svg id="cloud" width="800" height="600">
<defs>
<marker id="arrow" viewbox="0 -5 10 10" refX="18" refY="0"
markerWidth="6" markerHeight="6" orient="auto">
<path d="M0,-5L10,0L0,5Z">
</marker>
</defs>
</svg>
<link href="cloud.css" rel="stylesheet" type="text/css" />
<script src="cloud.js" type="text/javascript"></script>
</body>
</html>

动态生成标记标签时出现了什么问题。为什么不显示标记?我想动态生成标记标签。这个怎么做?

最佳答案

问题是,通过使用 jquery 添加 SVG 元素作为文本,它们在错误的命名空间中被解释。也就是说,HTML 中没有 defsmarker 等元素,因此它们什么都不做。这些元素仅在 SVG 命名空间中有效,您在动态添加它们时无需指定。当它们被静态指定时,命名空间从上下文中是显而易见的。

有几种方法可以解决这个问题。您可以显式创建具有正确 namespace 的节点并将它们添加到适当的位置。然而,更简单的解决方案是使用 D3 添加这些元素,这将为您解决命名空间问题。代码会有点冗长,但很简单。

svg.append("defs").append("marker")
.attr("id", "arrow")
.attr("viewbox", "0 -5 10 10")
.attr("refX", 18)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");

已更新 jsfiddle here .

关于javascript - 使用 jquery 动态生成标记时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18635059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com